411 REFERENCE · Wikibooks
Introduction to Programming Languages/Catching exceptions
Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.
Try-Catch
The main exception handling mechanism is:try {
...
}
catch (...) {
...
}
Intuition Behind try
The:tryblock means: “Try to execute this”.
The:catchblock means: “If a certain error occurs, handle it here”.
Example
try {
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
System.out.println(i / j);
} catch (ArithmeticException a) {
System.out.println("You are dividing by zero!");
}
Execution Flow
Normal Case
try executes completely and catch is ignored.
Case With Exception
If:ArithmeticExceptionoccurs:
the try block is interrupted;
the matching catch block executes.
Complete Example
System.out.print("1, ");
try {
String s = null;
s.length();
}
catch (NullPointerException e) {
System.out.print("2, ");
}
System.out.println("3");Output: 1, 2, 3
Exceptions Across Methods
Exceptions can travel through multiple methods.
Example:void f() {
try {
g();
}
catch (ArithmeticException e) {
...
}
}If:g()throws an exception:
it propagates upward to f().
Long-Distance Throw
One of the greatest advantages of exceptions.
An exception can:
travel across many method calls;
without intermediate methods needing to handle it.
Visualization
main()
|
-> f()
|
-> g()
|
-> z()If:z()throws an exception:
z() stops;
then g() stops;
then f() receives the exception.
Multiple catch Blocks
We can handle different errors separately.try {
...
}
catch (ArithmeticException e) {
...
}
catch (ArrayIndexOutOfBoundsException e) {
...
}
Catch Order
Java uses the first compatible catch.
Important Example
catch (RuntimeException e)captures:
ArithmeticException;
NullPointerException;
etc.
Because they all derive from:RuntimeException