Exceptions handling
Introduction
Exceptions propagation
Java forces you to deal with checked exceptions. If a method declares a checked exception (i.e., an exception other than Error or RuntimeException), you must invoke it in a try-catch block or declare to throw the exception in the calling method.
For example, suppose that method p1 invokes method p2 and p2 may throw a checked exception (e.g., IOException), you have to write the code as shown in (a) or (b).
How to handle checked exceptions
- When a method encounters a condition it can't handle, that method should throw an exception. Then, users of the method can handle the exception in a way that's right for their programs.
- When a method calls another method that throws a checked exception, the method must either:
- throw the exception up to its calling method, or
- catch the exception and handle it
- Code that catches an exception is known as an exception handler.
- When an exception occurs, the runtime system looks for the appropriate exception handler.
- To do that, it looks through the stack trace, or call stack, which lists the methods that have been called until it finds a method that catches the exception.