Default Exception Handling

Whenever inside a method, if an exception has occurred, the method creates an object known as exception object and hands it off to the run-time system(JVM). An exception object is an instance of an exception class. It gets created and handed to the Java runtime when an exceptional event occurred that disrupted the normal flow of the application. This is called “to throw an exception” because in Java you use the keyword “throw” to hand the exception to the runtime. When a method throws an exception object, the runtime searches the call stack for a piece of code that handles it. The exception object contains name and description of the exception, and current state of the program where exception has occurred. Creating the Exception Object and handling it to the run-time system is called throwing an exception. There might be the list of the methods that had been called to get to the method where exception was occurred. This ordered list of the methods is called Call Stack. Now the following procedure will happen.

  1. The run-time system searches the call stack to find the method that contains block of code that can handle the occurred exception. The block of the code is called Exception handler.
  2. The run-time system starts searching from the method in which exception occurred, proceeds through call stack in the reverse order in which methods were called.
  3. If it finds appropriate handler then it passes the occurred exception to it. Appropriate handler means the type of the exception object thrown matches the type of the exception object it can handle.
  4. If run-time system searches all the methods on call stack and could have found the appropriate handler then run-time system handover the exception object to default exception handler, which is part of run-time system. This handler prints the exception information in certain format and terminates program abnormally.

See the below diagram to understand the flow of the call stack.

Figure 5.2: Call stack in Java
Image call-stack


\begin{lstlisting}
\par
// Java program to demonstrate how exception is thrown. ...
...ing str = null;
System.out.println(str.length());
\par
}
}
\end{lstlisting}

Output


\begin{lstlisting}
Exception in thread ''main'' java.lang.NullPointerException
at ThrowsExecp.main(File.java:8)
\end{lstlisting}

Let us see an example that illustrate how run-time system searches appropriate exception handling code on the call stack.


\begin{lstlisting}
\par
// Java program to demonstrate exception is thrown
// h...
...y zero)
System.out.println(ex.getMessage());
}
}
}
\par
\end{lstlisting}

Output


\begin{lstlisting}
/ by zero.
\end{lstlisting}