The try-catch-finally construct is Java's primary mechanism for trapping runtime exceptions and executing mandatory resource clean-up routines.
Statements that might generate a runtime error are enclosed within a try block. If an error occurs, JVM skips the remaining try block code and transfers control to the matching catch block:
public class TryCatchDemo {
public static void main(String[] args) {
System.out.println("Starting computation...");
try {
int a = 50;
int b = 0;
int result = a / b; // Throws ArithmeticException (/ by zero)
System.out.println("Result: " + result); // Skipped!
} catch (ArithmeticException e) {
System.err.println("Caught Error: Cannot divide a number by zero! Details: " + e.getMessage());
}
System.out.println("Program resumed smoothly after catch block!");
}
}
You can chain multiple catch blocks to handle different failure modes distinctly. Always order from subclass to superclass:
try {
int[] arr = new int[5];
arr[10] = 50; // Triggers ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("Mathematical error occurred.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of range!");
} catch (Exception e) {
// Catch-all fallback: Must be at the BOTTOM!
System.out.println("General exception caught: " + e.getMessage());
}
try {
// Operations that might throw multiple unrelated exceptions
processDatabaseRecord();
} catch (SQLException | IOException e) {
// Multi-catch: e is implicitly final!
System.err.println("Database or I/O failure: " + e.getMessage());
}
finally BlockThe finally block executes 100% of the time, ensuring database connections, file handles, and network sockets are closed:
try {
System.out.println("Inside try block");
return; // Even with early return, finally STILL EXECUTES!
} finally {
System.out.println("Inside finally block: Cleanup finished!");
}
Exam Question: "Under what exact condition will a finally block fail to execute in Java?"
Answer: The finally block will not execute ONLY if:
1. System.exit(0) is explicitly invoked, terminating the entire JVM process immediately.
2. A fatal OS crash, power failure, or JVM segmentation fault occurs.
3. The host thread executing the try block is killed or terminated by the OS kernel.
Now let us explore the difference between the throw and throws keywords. Proceed to: Java Throw vs Throws →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Declaring and throwing exceptions.
Modern resource management.
Handling custom domain errors.
Throwable overview.