Exception Handling Keywords and their utilities
Java provides several keywords to handle exceptions effectively, ensuring robust and error-resilient applications. Below are the key exception handling keywords and their utilities:
1. try
The try block is used to enclose code that might throw an exception. It identifies the section of code where exceptions may occur. The try block must be followed by either a catch block, a finally block, or both.
Utility: Encapsulates risky code to handle exceptions gracefully.
try {
int result = 10 / 0; // Risky code
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
2. catch
The catch block handles exceptions thrown in the try block. It specifies the type of exception to catch and provides a way to handle it. Multiple catch blocks can be used to handle different types of exceptions.
Utility: Catches and processes specific exceptions.
try {
int[] arr = new int[3];
System.out.println(arr[5]); // Risky code
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of bounds.");
}
Key Points:
- Specific Exception Handling:
- we can use multiple
catchblocks to handle different types of exceptions explicitly.- The most specific exception should be caught first, followed by more general exceptions. This is because Java checks the
catchblocks in the order they are written, and the first matching block is executed.- Generic Exception Handling:
- If no specific
catchblock matches the thrown exception, a genericcatchblock usingExceptioncan be used as a fallback to handle any other exceptions.- Order of Catch Blocks:
- The order of
catchblocks is important. More specific exceptions (e.g.,ArithmeticException,NullPointerException) must come before the genericExceptionblock. Otherwise, a compilation error will occur because the genericExceptionblock would catch all exceptions, making the specific blocks unreachable.
- Specific Exception Handling:
- we can use multiple
catchblocks to handle different types of exceptions explicitly. - The most specific exception should be caught first, followed by more general exceptions. This is because Java checks the
catchblocks in the order they are written, and the first matching block is executed.
- we can use multiple
- Generic Exception Handling:
- If no specific
catchblock matches the thrown exception, a genericcatchblock usingExceptioncan be used as a fallback to handle any other exceptions.
- If no specific
- Order of Catch Blocks:
- The order of
catchblocks is important. More specific exceptions (e.g.,ArithmeticException,NullPointerException) must come before the genericExceptionblock. Otherwise, a compilation error will occur because the genericExceptionblock would catch all exceptions, making the specific blocks unreachable.
- The order of
Example:
public class MultipleCatchExample {
public static void main(String[] args) {
try {
int[] arr = new int[3];
arr[5] = 10; // This will throw ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception caught: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out of Bounds Exception caught: " + e.getMessage());
} catch (Exception e) {
System.out.println("Generic Exception caught: " + e.getMessage());
}
}
}
3. finally
The finally block contains code that will always execute, regardless of whether an exception is thrown or not. It is typically used for cleanup operations, such as closing files or releasing resources.
Utility: Ensures cleanup actions are performed.
try {
int result = 10 / 2;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Error occurred.");
} finally {
System.out.println("Execution completed.");
}
4. throw
The throw keyword is used to explicitly throw an exception. It is often used to throw custom exceptions or re-throw exceptions caught in a catch block.
Utility: Manually triggers an exception.
public void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or above.");
}
}
5. throws
The throws keyword is used in method declarations to indicate that a method might throw one or more exceptions. It delegates the responsibility of handling the exception to the calling method.
Utility: Declares exceptions that a method can throw.
public void readFile(String fileName) throws IOException {
FileReader file = new FileReader(fileName);
}
6. try-with-resources
Introduced in Java 7, the try-with-resources statement is used to automatically close resources (e.g., files, streams) that implement the AutoCloseable interface. It eliminates the need for a finally block for resource cleanup.
Utility: Simplifies resource management.
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
System.out.println(br.readLine());
} catch (IOException e) {
System.out.println("Error reading file.");
}
Summary:
try: Encapsulates risky code.catch: Handles specific exceptions.finally: Ensures cleanup actions are performed.throw: Explicitly throws an exception.throws: Declares exceptions a method might throw.try-with-resources: Automatically manages resource cleanup.
