🧠 Java Quiz

Java Exception Handling

React to errors instead of crashing.

What's an exception?

An exception is an object that represents something going wrong — a file not found, a division by zero, a network failure. When this happens, normal flow stops and an exception is "thrown".

try / catch

Wrap risky code in try; handle problems in catch:

Basic try/catch
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero: " + e.getMessage());
}
System.out.println("Program continues...");

Multiple catch blocks

Catch specific exceptions first
try {
    String input = null;
    int n = Integer.parseInt(input);
} catch (NumberFormatException e) {
    System.out.println("Bad number format");
} catch (NullPointerException e) {
    System.out.println("Input was null");
} catch (Exception e) {
    System.out.println("Something else went wrong: " + e);
}

Multi-catch (Java 7+)

Pipe-separated
try { ... }
catch (NumberFormatException | NullPointerException e) {
    System.out.println("Bad input: " + e.getMessage());
}

finally — always runs

The finally block runs whether or not an exception was thrown. Use it for cleanup.

finally
FileReader f = null;
try {
    f = new FileReader("data.txt");
    // read file...
} catch (IOException e) {
    System.out.println("Read failed: " + e.getMessage());
} finally {
    if (f != null) {
        try { f.close(); }
        catch (IOException ignored) {}
    }
}

try-with-resources (Java 7+)

For anything that implements AutoCloseable (files, sockets, database connections), use try-with-resources. Resources auto-close even on exception.

try-with-resources
try (FileReader f = new FileReader("data.txt")) {
    // use f
} catch (IOException e) {
    e.printStackTrace();
}
// f is closed automatically — no finally needed

Throwing exceptions

throw
public void setAge(int age) {
    if (age < 0) {
        throw new IllegalArgumentException("Age cannot be negative");
    }
    this.age = age;
}

Checked vs unchecked

Java has two kinds of exceptions:

throws clause
public void readFile(String path) throws IOException {
    new FileReader(path);  // IOException is checked — must throw or catch
}

Custom exceptions

Your own type
public class InsufficientFundsException extends RuntimeException {
    public InsufficientFundsException(String msg) {
        super(msg);
    }
}

// Use it:
if (amount > balance) {
    throw new InsufficientFundsException("Need $" + amount);
}
Don't catch and ignore Empty catch blocks (catch (Exception e) {}) hide bugs. At minimum log the exception. At best, handle it meaningfully or let it propagate.