In Java, you can handle exceptions using try-catch blocks. This allows you to catch and handle specific types of exceptions that may occur during the execution of your code. Here’s the basic syntax of a try-catch block:
try {
// Code that may throw an exception
} catch (ExceptionType1 e1) {
// Exception handling for ExceptionType1
} catch (ExceptionType2 e2) {
// Exception handling for ExceptionType2
} finally {
// Code that will always execute, regardless of whether an exception occurred or not
}
Here’s how the try-catch block works:
- The code that may throw an exception is enclosed within the
tryblock. - If an exception occurs within the
tryblock, it is caught by the appropriatecatchblock. You can have multiplecatchblocks to handle different types of exceptions. Eachcatchblock specifies the type of exception it can handle. - If an exception is thrown and a matching
catchblock is found, the code within thatcatchblock is executed. - After the
catchblock is executed (or if no exception occurred), the code within thefinallyblock is executed. Thefinallyblock is optional and is typically used for cleanup tasks that need to be performed, such as closing resources. - If an exception occurs and there is no matching
catchblock, the exception is propagated up the call stack to the next higher-leveltry-catchblock, or if none is found, the program terminates with an error.
Here’s an example to illustrate how to use try-catch blocks:
try {
// Code that may throw an exception
int result = 10 / 0; // Division by zero will throw an ArithmeticException
System.out.println("Result: " + result); // This line will not be executed
} catch (ArithmeticException e) {
// Exception handling for ArithmeticException
System.out.println("An arithmetic exception occurred: " + e.getMessage());
} finally {
// Cleanup code that will always execute
System.out.println("Finally block executed.");
}
In this example, the division by zero will throw an ArithmeticException, which is caught by the corresponding catch block. The exception message is printed, and then the finally block is executed, printing the “Finally block executed.” message.
It’s important to catch and handle exceptions appropriately to prevent unexpected program termination and provide meaningful error messages or take necessary actions based on the specific exception type.




