⚠️ Exception Handling
Learn how to deal with runtime errors gracefully using try-catch blocks, exceptions, and the try-with-resources statement.
1. Error vs Exception
An Exception is an unwanted or unexpected event occurring during program execution that disrupts the normal flow of instructions. Java provides a robust mechanism to handle these so the program can recover or terminate gracefully.
An Error represents serious problems that a reasonable application should not try to catch (e.g., OutOfMemoryError, StackOverflowError).
2. Exception Hierarchy
Throwable
/ \
/ \
Error Exception
/ \
/ \
IOException RuntimeException
SQLException / \
/ \
NullPointerException ArithmeticException
- Checked Exceptions: Exceptions checked at compile-time (e.g., IOException). You MUST handle them using try-catch or declare them using
throws. - Unchecked Exceptions: Exceptions occurring at runtime (subclasses of RuntimeException). Not checked at compile-time (e.g., NullPointerException).
3. Try-Catch & Finally
public class BasicExceptionDemo { public static void main(String[] args) { try { int result = 10 / 0; // Throws ArithmeticException System.out.println(result); } catch (ArithmeticException e) { System.out.println("Cannot divide by zero!"); } finally { System.out.println("Finally block always executes."); } } }
4. Custom Exceptions & Throw/Throws
Use throw to explicitly throw an exception object. Use throws in a method signature to indicate the method might throw checked exceptions.
// Custom checked exception class InsufficientFundsException extends Exception { public InsufficientFundsException(String message) { super(message); } } public class CustomExceptionDemo { static void withdraw(double balance, double amount) throws InsufficientFundsException { if (amount > balance) { throw new InsufficientFundsException("Not enough money!"); } System.out.println("Withdrawal successful."); } public static void main(String[] args) { try { withdraw(100, 500); } catch (InsufficientFundsException e) { System.out.println("Error: " + e.getMessage()); } } }
5. Try-with-Resources (Java 7)
Automatically closes resources (like files, streams, or database connections) that implement the AutoCloseable interface, removing the need for a finally block just to close them.
import java.io.*; public class TryWithResourcesDemo { public static void main(String[] args) { // Scanner or Streams declared here are automatically closed try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) { System.out.println(br.readLine()); } catch (IOException e) { System.out.println("File error: " + e.getMessage()); } } }