Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

  • exception is an event that disrupts the normal flow of a program during execution, typically caused by errors such as invalid input, file not found, or network issues.
  • in java, exceptions are objects derived from the java.lang.Throwable class, which has two main subclasses.
  • java provides a structured way to handle exceptions using the try-catch mechanism, with optional finally and throw constructs.

handling exceptions

using try-catch

  • the catch block executes only if the specified exception.
  • use e.getMessage() to get the exception’s error messages or e.printStackTrace() for a detailed stack trace.
  • multiple catch can be used to catch multiple exceptions.
public class Main {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // Throws ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Error: Division by zero");
            System.out.println("Message: " + e.getMessage());
        }
        System.out.println("Program continues...");
    }
}

using multiple catches

try {
    String str = null;
    System.out.println(str.length()); // Throws NullPointerException
    int[] arr = new int[2];
    arr[3] = 10; // Throws ArrayIndexOutOfBoundsException
} catch (NullPointerException e) {
    System.out.println("Null reference: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Invalid index: " + e.getMessage());
}

catching superclass exceptions

try {
    int result = 10 / 0;
} catch (Exception e) {
    System.out.println("General error: " + e.getMessage());
}

using finally

the finally block contains code that executes regardless of whatever an exception is thrown or caught

public class Main {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // Throws ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        } finally {
            System.out.println("Cleanup in finally block");
        }
    }
}

types of exceptions

checked exceptions

  • must be declared in a method’s throws clause or handled in a try-catch block.
  • compile time checking ensures they are addressed.
  • extend java.lang.Exception
  • ex - IOException, SQLException, classNotFoundException.

unchecked exception

  • doesnt require explicit handling or declaration
  • typically indicates programming errors or runtime issues.
  • extend java.lang.RuntimeException
  • ex - NullPointerException, ArrayIndexOutOfBoundsException, etc.

throwing exceptions

the throw keyword is used to explicitly throw an expression either built in or custom exception.

public class Main {
    public static void checkAge(int age) throws IllegalArgumentException {
        if (age < 18) {
            throw new IllegalArgumentException("Age must be 18 or older");
        }
        System.out.println("Access granted");
    }

    public static void main(String[] args) {
        try {
            checkAge(15);
        } catch (IllegalArgumentException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

writing exception subclasses

// Custom checked exception
class InvalidBalanceException extends Exception {
    public InvalidBalanceException(String message) {
        super(message);
    }

    public InvalidBalanceException(String message, Throwable cause) {
        super(message, cause);
    }
}

// Custom unchecked exception
class InsufficientFundsException extends RuntimeException {
    public InsufficientFundsException(String message) {
        super(message);
    }
}

class BankAccount {
    private double balance;

    public void withdraw(double amount) throws InvalidBalanceException {
        if (amount < 0) {
            throw new InvalidBalanceException("Withdrawal amount cannot be negative");
        }
        if (amount > balance) {
            throw new InsufficientFundsException("Not enough funds");
        }
        balance -= amount;
    }

    public void setBalance(double balance) throws InvalidBalanceException {
        if (balance < 0) {
            throw new InvalidBalanceException("Balance cannot be negative");
        }
        this.balance = balance;
    }
}

public class Main {
    public static void main(String[] args) {
        BankAccount account = new BankAccount();
        try {
            account.setBalance(100);
            account.withdraw(150); // Throws InsufficientFundsException
        } catch (InvalidBalanceException e) {
            System.out.println("Balance Error: " + e.getMessage());
        } catch (InsufficientFundsException e) {
            System.out.println("Funds Error: " + e.getMessage());
        }
    }
}