</>
Skip to content
Java lessons (41/47)

Java — Exceptions

Basic try-catch

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

Multiple catch blocks

try {
    String s = null;
    s.length();
} catch (NullPointerException e) {
    System.out.println("Null pointer");
} catch (Exception e) {
    System.out.println("General error");
} finally {
    System.out.println("Always runs");
}

Custom exceptions

class InsufficientFundsException extends Exception {
    private double amount;

    InsufficientFundsException(double amount) {
        super("Insufficient funds: need " + amount);
        this.amount = amount;
    }

    double getAmount() { return amount; }
}

class BankAccount {
    private double balance;

    void withdraw(double amount) throws InsufficientFundsException {
        if (amount > balance) {
            throw new InsufficientFundsException(amount - balance);
        }
        balance -= amount;
    }
}

Try-with-resources

import java.io.*;

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} // Auto-closed

Common exceptions

ExceptionWhen
NullPointerExceptionNull reference
ArrayIndexOutOfBoundsExceptionInvalid array index
ClassNotFoundExceptionClass not found
IOExceptionI/O error
NumberFormatExceptionInvalid number format
IllegalArgumentExceptionInvalid argument
IllegalStateExceptionInvalid state

Mini Practice

Write Java code that:

  1. Creates a custom exception
  2. Uses try-with-resources for file operations
  3. Demonstrates multi-catch with |

Up Next

In the next lesson, you'll learn about Collections — Lists, Sets, and Maps.

Related Topics

Frequently Asked Questions about Exceptions

What is Exceptions in Java?

Exceptions is a fundamental concept in Java. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Exceptions?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Exceptions.

Why is Exceptions important in Java?

Exceptions is essential for Java development. Understanding this concept will help you write better code and solve real-world problems more effectively.