Java Error and Exception
Throwable has two main branches: Exception and Error. A form can recover from an expected bad entry. An Error such as OutOfMemoryError signals a serious problem that an ordinary form handler should usually let propagate.
A simple example
Error and Exception
- Start with An IllegalArgumentException and an AssertionError
- Do this Test membership in Exception
- Result First yes, second no
Syntax
catch (NumberFormatException invalid) { /* explain the input rule */ }
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaSee which failures belong to the Exception branch
A caller needs to decide which failures its handler is meant to catch. Inspect the exception hierarchy before choosing the handler's scope so serious runtime conditions are not grouped indiscriminately with ordinary errors.
import java.io.IOException;
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(Exception.class.isAssignableFrom(NumberFormatException.class));
System.out.println(RuntimeException.class.isAssignableFrom(IOException.class));
System.out.println(Exception.class.isAssignableFrom(OutOfMemoryError.class));
}
}
true false false
The first line identifies a form conversion failure as an Exception. The second shows that IOException is outside the RuntimeException hierarchy. The third checks the type of a serious error without causing one.
Choose a handler for a bad attendance count
A school import receives the word ten in a numeric column. The clerk can correct that row, so the importer handles the parsing failure narrowly and reports the row for correction.
class Main {
public static void main(String[] args) throws Exception {
try {
System.out.println(Integer.parseInt("ten"));
} catch (NumberFormatException invalid) {
System.out.println("Correct the attendance row");
}
}
}
Correct the attendance row
A targeted handler matches the recoverable parsing condition. Serious JVM errors remain outside its scope.
Read a donation total
The library has a signed-off box count written as decimal digits. Parse the entire quantity as a base-ten integer. Let the clerk correct a rejected record.
Code and output in Java
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;
class Main {
public static void main(String[] args) throws Exception {
try {
Integer.parseInt("24");
System.out.println("Quantity accepted");
} catch (NumberFormatException problem) {
System.out.println("Review quantity");
}
}
}
Quantity accepted
What to watch for
IOException is a checked exception. NumberFormatException is an unchecked RuntimeException. Error is also unchecked and is outside the Exception branch.