Java Exception Handling Handling Exceptions
Learning objective: By the end of this lesson, you’ll be code exception handling statements using try-catch-finally statement blocks
The try-catch-finally block
Java provides a sequential structure to handle exceptions:
try {
// Code that has the potential to throw an exception needs to be enclosed
// inside this block
} catch (ExceptionType e) {
// Code to handle the exception encountered in the try block needs to reside
// in this block
} finally {
// An optional block that contains code that will always run, whether or not
// an exception occurred.
}
Control flow of the try-catch-finally block
Exception occurrence flow
- The program execution enters the
tryblock. - If an exception occurs, the remaining code in the
tryblock is skipped. - The program execution jumps to the
catchblock. - After the
catchblock executes, the program moves to thefinallyblock (if it exists).
Exception non-occurrence flow
- The program execution enters the
tryblock. - Executes all the code in the
tryblock. - Skips the
catchblock. - Executes the
finallyblock (if it exists).
Demo of try-catch-finally block
Here is a program that gracefully handles an ArithmeticException (division by zero) exception gracefully by using try-catch-finally block.
public class SafeDivision {
public static void main(String[] args) {
int a = 15;
int b = 0;
try {
System.out.println("Attempting to divide " + a + " by " + b);
int result = a / b;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
} finally {
System.out.println("End of division operation.");
}
}
}
Exceptions
5 minUsing the sample code given in this lesson, let’s discuss the answers to the following questions:
- Can we have a
catchorfinallyblock without atryblock? - Can we have a
tryblock without acatchorfinallyblock? - Can we code any statements in the space between the
try,catch, andfinallyblocks? - Can we have multiple
catchblocks for a singletryblock?