Java Exceptions
An exception is Java's way of signalling that something unexpected happened while your program was running, such as dividing by zero or trying to open a file that does not exist. Learning to recognise and handle exceptions is what turns a fragile program into a reliable one.
When a Java program hits a situation it cannot deal with normally, it stops what it is doing and creates an object that describes the problem. This object is called an exception. If nobody deals with it, the program crashes and prints a message called a stack trace. The good news is that Java gives you tools to catch these problems and respond gracefully instead of letting your app fall over.
The exception hierarchy
Every exception in Java is an object that ultimately extends the Throwable class. Below Throwable there are two important branches: Error, which represents serious problems your code normally should not try to recover from (like running out of memory), and Exception, which represents conditions your program can and often should handle. Within Exception there is a special group called RuntimeException, used for programming mistakes such as accessing an array index that does not exist.
The difference between checked and unchecked exceptions matters. Checked exceptions must either be handled with a try-catch or declared with a throws clause, or your code will not compile. Unchecked exceptions do not force you to do anything, but they will still crash your program if ignored.
An exception that crashes the program
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
// There is no index 5, so Java throws an exception here
System.out.println(numbers[5]);
System.out.println("This line never runs");
}
}
// Output:
// Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
// Index 5 out of bounds for length 3Notice that the line after the bad array access never printed. The moment an exception is thrown, Java abandons the normal flow and looks for something to handle it. If nothing does, execution ends.
Throwing your own exceptions
You are not limited to the exceptions Java throws for you. Using the throw keyword you can raise an exception yourself when a rule in your program is broken. This is useful for validating input, such as rejecting an age that does not make sense.
Using throw to enforce a rule
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older");
}
System.out.println("Access granted");
}
public static void main(String[] args) {
checkAge(15); // throws IllegalArgumentException
}
}- An exception is an object describing a problem that interrupts normal flow.
- Checked exceptions must be handled or declared; unchecked ones do not have to be.
- The throw keyword lets you raise an exception intentionally.
- Uncaught exceptions stop the program and print a stack trace.
Exercise: Java Exceptions
What distinguishes a checked exception from an unchecked exception in Java?