Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to Java
Java Exception Handling Guide

Java Exception Handling Guide

Java2,618 viewsBy Admin
javaexceptionhandling

Exceptions in Java

Exceptions signal errors during execution. Java uses try/catch/finally and distinguishes checked vs unchecked exceptions.

try/catch/finally

try {
    int[] arr = new int[3];
    arr[5] = 10; // throws
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Bad index: " + e.getMessage());
} finally {
    System.out.println("Always runs");
}

Checked vs Unchecked

TypeMust handle?Example
CheckedYes (compile)IOException
UncheckedNoNullPointerException

Throwing Exceptions

public void setAge(int age) {
    if (age < 0) throw new IllegalArgumentException("Age < 0");
}

try-with-resources

try (BufferedReader r = new BufferedReader(new FileReader("f.txt"))) {
    return r.readLine();
} // file auto-closed

FAQs

Should I catch Exception broadly?

No — catch specific types. Broad catches hide bugs. More in our Java section.

What is the finally block for?

Cleanup that must run whether or not an exception occurred.