Back to course

Try-Catch-Finally Blocks and Custom Exceptions

Java Mastery: From Zero to Professional Developer (50-Lesson Journey)

Lesson 34: Try-Catch-Finally Blocks and Custom Exceptions

1. The try-catch-finally Mechanism

The try Block

Contains the code that might throw an exception.

The catch Block

Executed if an exception of the specified type occurs in the try block. It contains the recovery or error reporting logic.

The finally Block

Always executes, regardless of whether an exception was thrown or caught. Often used for cleanup tasks (e.g., closing file streams).

java public void divide(int numerator, int denominator) { try { // Code that might fail int result = numerator / denominator; System.out.println("Result: " + result); } catch (ArithmeticException e) { // Handle the error gracefully System.err.println("Error: Cannot divide by zero. Message: " + e.getMessage()); } finally { // Cleanup code runs every time System.out.println("Division attempt completed."); } }

Catching Multiple Exceptions (Multi-catch)

Since Java 7, you can catch multiple exception types in a single catch block if the handling logic is identical.

java catch (IOException | SQLException e) { System.err.println("A related IO/SQL error occurred."); }

2. Creating Custom Exceptions

If the built-in Java exceptions don't accurately describe the error, you can define your own.

  • To create a Checked Exception, extend Exception.
  • To create an Unchecked Exception, extend RuntimeException.

java public class InsufficientFundsException extends Exception { // Custom constructor public InsufficientFundsException(String message) { super(message); } }

// To throw it: // throw new InsufficientFundsException("Balance too low");