Sub topic 1
What Happens When Things Go Wrong
What an Exception Is
An exception is an object that Java creates when something goes wrong while a program runs. Dividing by zero is one example. Reading a file that does not exist is another.
When an exception happens, Java stops running the current line. It jumps out of the method and keeps going up to the method that called it, and so on. This is called propagation. If no code handles the exception, the program crashes and prints an error.
The Exception Family Tree
Every exception comes from a class called Throwable. It has two main branches.
- Error means a serious problem, such as running out of memory. You usually do not handle these.
- Exception means a problem your program can often recover from.
Checked vs Unchecked Exceptions
| Kind | What it is | Example |
|---|---|---|
| Checked | The compiler makes you handle it or declare it | `IOException` |
| Unchecked | A `RuntimeException` or one of its subclasses. The compiler does not force you to handle it | `NumberFormatException` |
Checked exceptions are for problems outside your control, like a missing file. Unchecked exceptions usually point to a bug or to bad input.
Catching Exceptions with try and catch
A try block holds code that might fail. A catch block runs only if that code throws a matching exception.
public class ParseDemo {
public static void main(String[] args) {
try {
int n = Integer.parseInt("42x");
System.out.println("Parsed: " + n);
} catch (NumberFormatException e) {
System.out.println("Not a number: " + e.getMessage());
}
System.out.println("Program continues");
}
}The text "42x" is not a number, so parseInt throws. The "Parsed" line is skipped, the catch block runs, and the program keeps going.
Handling Several Exception Types
You can write several catch blocks, one per exception type. If two types need the same handling, a multi-catch joins them with |:
public class MultiCatchDemo {
public static void main(String[] args) {
try {
int[] nums = {1, 2};
System.out.println(nums[5] / 0);
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println("Problem: " + e);
}
}
}Exercise
Is NumberFormatException checked or unchecked, and how do you know?
Show answer
It is unchecked. It is a subclass of RuntimeException, so the compiler does not force you to catch it or declare it.