Java Exception Handling: try, catch, finally Blocks
In Java, exception handling is done using the try, catch, and finally blocks.
try Block:
The try block contains the code that might throw an exception. It is followed by one or more
catch blocks or a finally block.
try {
// Code that might throw an exception
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// Handling the specific exception
System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
// Handling a more general exception
System.out.println("An error occurred: " + e.getMessage());
}
catch Block:
The catch block is used to catch and handle exceptions. It specifies the type of exception it can handle,
and multiple catch blocks can be used to handle different types of exceptions.
finally Block:
The finally block contains code that will be executed regardless of whether an exception is thrown or not.
It is optional, but if present, it will always execute.
finally {
// Code that always executes (optional)
System.out.println("This block always executes.");
}
Note:
The finally block is often used for cleanup operations, such as closing resources, that need to be
executed regardless of whether an exception occurs or not.