Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Handling Exceptions in Java

In this lesson, you will learn

  • What is an Exception
  • Exceptions Handling Mechanism
  • Examples

 

What is Exception

Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.

Reference: https://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html

The following are the common exceptions thrown by JVM

  • Dividing an integer by zero
  • Accessing an array element with an illegal index
  • Accessing an out-of-bounds element from an array
  • Attempted to use a negative size of an array
  • Null pointer access
  • Passing an illegal or inappropriate argument.
  • The element being requested does not exist.
  • Attempted to convert a string to a numeric types

Note: You need to handle and manage the above exceptions; otherwise, the program may be terminated suddenly without showing the desired output.

 

Why Exceptions are Important:

  • Robustness: They make your program more robust by handling unexpected situations.
  • Error Reporting: They provide a structured way to report errors.
  • Code Clarity: They separate error-handling code from the main program logic, making your code cleaner.

 

Exception Handling Mechanism

Java provides the following keywords for handling exceptions: try, catch, finally, throw and throws.

  1. try:

    • The try block encloses the code that might throw an exception.
  2. catch:

    • The catch block handles the exception that is thrown within the corresponding try block.
    • You can have multiple catch blocks to handle different types of exceptions.
  3. finally:

    • The finally block contains code that is always executed, regardless of whether an exception is thrown or caught.
    • It’s typically used for cleanup operations, such as closing resources.
  4. throw:

    • The throw keyword is used to explicitly throw an exception.
  5. throws:

    • The throws keyword is used in method declarations to indicate that a method might throw a particular exception.

 

Understanding the ‘try-catch’ Block

  • The try-catch block is used to catch and handle exceptions.
  • The code that might throw an exception is placed inside the try block and the code to handle the exception is placed inside the catch block.

The following is the syntax of exception handling through the try-catch block.

 

Syntax: Exception Handling Using ‘try-catch’ Block

try {
    // Code that might throw an exception
} catch (ExceptionType1 e1) {
    // Handle ExceptionType1
} catch (ExceptionType2 e2) {
    // Handle ExceptionType2
} finally {
    // Code that always executes (cleanup, etc.)
}

 

The following figure shows the working process of try-catch-finally block to handle the exception in Java.

ExceptionHandling

 

Understanding the Working Process of ‘try-catch’ Block

If an exception is raised within the try block, the appropriate exception handler that is associated with the try block processes the exception.

In Java, the catch block is used to handle exceptions and is known as an exception handler.

A try block must have at least one catch block that follows the try block, immediately. No other statements are allowed between try-and-catch blocks.

The catch block specifies the exception type that you need to catch or handle.

 

For Example

catch(ArithmeticException e) { //Statements }
//This catch block will handle the ArithmeticException
// E.g. '/' division by zero.

 

Important Points!

The try block can generate more than one type of exception. If any statement generates an exception, the remaining statements in the try block are skipped and control will be transferred to the appropriate catch block.

The catch block can also have more than one statement that handles the exception.

 

Consider the following example where you will accept two integers from the user, and perform some arithmetic operation.

Example: Performing Arithmetic Operation

import java.util.Scanner;
public class ExceptionExample {

	public static int divide(int numerator, int denominator) {
        return numerator / denominator;
    }

	public static void main(String[] args) {
		int num1, num2, result;
		System.out.println("Performing arithmetic operation->>");
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter the 1st number");
		num1 = scanner.nextInt();
		System.out.println("Enter the 2nd number");
		num2 = scanner.nextInt();
		//Call the divide function
		result = divide(num1,num2);
		System.out.println("Result: " + result);
	}
}

Output

Test Case -1

Performing arithmetic operation->>
Enter the 1st number
25
Enter the 2nd number
5
Result: 5

 

Test Case -2: If the user provides an input other than an integer value, an exception is raised and the program terminates abnormally as shown in the code snippet.

Performing arithmetic operation->>
Enter the 1st number
10
Enter the 2nd number
Hi
Exception in thread "main" java.util.InputMismatchException
	at java.base/java.util.Scanner.throwFor(Scanner.java:939)
	at java.base/java.util.Scanner.next(Scanner.java:1594)
	at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
	at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
	at stringdemo.ExceptionExample.main(ExceptionExample.java:18)

 

Test Case -3: If the value of the denominator is zero.

Performing arithmetic operation->>
Enter the 1st number
10
Enter the 2nd number
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at stringdemo.ExceptionExample.divide(ExceptionExample.java:8)
	at stringdemo.ExceptionExample.main(ExceptionExample.java:20)

 

To resolve the above problem and issue, you will use the exception handling mechanism using the try-catch block. Let’s apply the try-catch to the above code.

 

Example – Adding a ‘try-catch’ to the above code

import java.util.Scanner;
public class ExceptionExample {
	
	public static int divide(int numerator, int denominator) {
        return numerator / denominator;
    }

	public static void main(String[] args) {
		int num1, num2, result;
		System.out.println("Performing arithmetic operation->>");
		try {
			Scanner scanner = new Scanner(System.in);
			System.out.println("Enter the 1st number");
			num1 = scanner.nextInt();
			System.out.println("Enter the 2nd number");
			num2 = scanner.nextInt();
			//Call the divide function
			result = divide(num1,num2);	
			System.out.println("Result: " + result);
			scanner.close();
		} catch (Exception e) {
			System.out.println("Exception Caught: " + e);
		}
	}
}

Explanation

A try block is used to monitor the user input in the above code. If the user enters an input that is not an integer or invalid value then an exception is raised and handled by a catch block.

However, the exception is successfully handled by the catch block and displays a message “Exception Caught” and the abnormal termination of the program is handled successfully.

The catch(Exception e), here Exception is a superclass and can manage all types of exception.

 

Output: After Exception Handling

Test Case-1

Performing arithmetic operation->>
Enter the 1st number
10
Enter the 2nd number
0
Caught Exception: java.lang.ArithmeticException: / by zero

 

Test Case – 2

Performing arithmetic operation->>
Enter the 1st number
10
Enter the 2nd number
hi
Caught Exception: java.util.InputMismatchException

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

5.0
5.0 out of 5 stars (based on 3 reviews)
Excellent100%
Very good0%
Average0%
Poor0%
Terrible0%

 

 

01/06/2025

well explained

07/05/2025

Nicely Explained

15/04/2025

good

 

 

Submit a Review