exception is an error in the program that occurs at run time. It disrupts the normal flow of the program's instructions.
When an error occurs, an
exception object is created by the calling method. An exception is a java object that derives from the
Creating an exception object and handing it off to the runtime system is called
throwing an exception.
Here is a simple program that throws an exception after we try to read outside the bounds of the array :
and here is the screen shot from an IDE showing the
call stack :
1 - The
main method was called first
2 - The
main method then called the
The stack is a
LIFO(Last-In-First-Out), the last method to be called will be on top of the stack. When an error occurs, the runtime system unwinds the call stack, looking for a method that can handle the error.
The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The set of methods is called the
The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an
exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler.
The exception handler chosen is said to
catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, the runtime system(and, consequently, the program) terminates. This is also called