We can do this by using try/catch/finally blocks
You place the normal processing code in try block
You put the code to deal with exceptions that might arise in try block in catch block
Code that must be executed no matter what happens must be place in finally block
In Java, you can intercept and control exceptions using the try-catch block. The basic idea is to enclose the code that might throw an exception within a try block, and then use one or more catch blocks to handle different types of exceptions.
Here’s a basic structure of a try-catch block:
try {
// Code that may throw an exception
} catch (ExceptionType1 e1) {
// Handle ExceptionType1
} catch (ExceptionType2 e2) {
// Handle ExceptionType2
} catch (Exception e) {
// Handle other types of exceptions
} finally {
// Optional: Code that will be executed whether an exception occurs or not
}
- The
try
block contains the code that might throw an exception. - The
catch
blocks specify how to handle different types of exceptions. You can have multiple catch blocks for handling different exception types. - The
finally
block is optional and contains code that will be executed whether an exception occurs or not. It is often used for cleanup operations.
Here’s a brief example:
try {
// Code that may throw an exception
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
// Handle ArithmeticException
System.out.println("Cannot divide by zero");
} catch (Exception e) {
// Handle other types of exceptions
System.out.println("An exception occurred: " + e.getMessage());
} finally {
// Optional: Code that will be executed whether an exception occurs or not
System.out.println("This will be executed regardless of an exception");
}
In this example, if an ArithmeticException
occurs, the first catch block will be executed. If any other type of exception occurs, the second catch block will be executed. The finally
block will be executed regardless of whether an exception occurs or not.