Try / Catch / Finally
Java Exception Handling
Master the art of graceful error handling in Java using structured try/catch/finally blocks to write robust, crash-resistant programs.
What Is an Exception?
An exception is an event that disrupts the normal flow of a program's execution. When something goes wrong at runtime: dividing by zero, accessing a null reference, or reading a missing file: Java creates an exception object and throws it.
Why Handle Exceptions?
Exception handling lets you anticipate problems and respond gracefully instead of crashing. It separates your normal logic from your error-recovery logic, making code cleaner and more maintainable.
Java's Exception Hierarchy
The Try/Catch Syntax
try { // Code that might throw an exception int result = 10 / 0; } catch (ArithmeticException e) { // Handle the exception System.out.println("Cannot divide by zero!"); }
The Finally Block
Scanner scanner = null; try { scanner = new Scanner(new File("data.txt")); String line = scanner.nextLine(); } catch (FileNotFoundException e) { System.out.println("File not found!"); } finally { // Always runs: exception or not if (scanner != null) scanner.close(); }
Execution Flow
Checked vs Unchecked Exceptions
| Checked | Unchecked | |
|---|---|---|
| When detected | Compile time | Runtime only |
| Must handle? | Yes: catch or declare | No: optional |
| Extends | Exception (directly) | RuntimeException |
| Examples | IOException, SQLException | NullPointerException, IndexOutOfBoundsException |
| Typical cause | External resources | Programming bugs |
Multiple Catch Blocks
try { int[] arr = {1, 2, 3}; int val = arr[10]; // throws ArrayIndexOutOfBoundsException int x = 10 / 0; // throws ArithmeticException } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Index out of bounds!"); } catch (ArithmeticException e) { System.out.println("Math error!"); } catch (Exception e) { System.out.println("Something else went wrong."); }
How to Apply Try/Catch/Finally
Example 1: Safe Division
public static int safeDivide(int a, int b) { try { return a / b; } catch (ArithmeticException e) { System.out.println("Error: division by zero"); return 0; // fallback value } }
Example 2: File Reading with Finally
BufferedReader reader = null; try { reader = new BufferedReader( new FileReader("scores.txt")); String line = reader.readLine(); System.out.println(line); } catch (FileNotFoundException e) { System.out.println("File not found!"); } catch (IOException e) { System.out.println("Error reading file."); } finally { try { if (reader != null) { reader.close(); // This can also throw an exception! } } catch (IOException e) { e.printStackTrace(); } }
Example 3: Parsing User Input
public static int parseAge(String input) { try { int age = Integer.parseInt(input); if (age < 0 || age > 150) { throw new IllegalArgumentException( "Age out of range"); } return age; } catch (NumberFormatException e) { System.out.println("Not a valid number!"); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } return -1; // indicates invalid input }
Modern Java: Try-With-Resources
// Resources declared in () are auto-closed try (BufferedReader reader = new BufferedReader( new FileReader("data.txt"))) { String line = reader.readLine(); System.out.println(line); } catch (IOException e) { System.out.println("I/O error: " + e.getMessage()); } // No finally needed: reader is auto-closed!
Common Mistakes
Summary Cheat Sheet
| Block | Purpose | Runs When |
|---|---|---|
| try | Contains risky code | Always attempted |
| catch | Handles specific exception | Only if matching exception thrown |
| finally | Cleanup / resource release | Always (success or failure) |
| try-with-resources | Auto-close resources | Replaces manual finally |
Question 1 of 5
What happens if an exception is thrown inside a try block and there is no matching catch block?
Question 2 of 5
try {
System.out.println("A");
int x = 10 / 0;
System.out.println("B");
} catch (ArithmeticException e) {
System.out.println("C");
} finally {
System.out.println("D");
}
System.out.println("E");
What is printed by this code?
Question 3 of 5
Which statement about the finally block is correct?
Question 4 of 5
Why does Java require you to catch IOException but not NullPointerException?
Question 5 of 5
try {
String s = null;
System.out.println(s.length());
} catch (NullPointerException e) {
System.out.println("Caught NPE");
} catch (Exception e) {
System.out.println("Caught Exception");
} finally {
System.out.println("Done");
}
What is the output of this code?