Exception handling statements
As we have explained in the introduction, an unexpected condition can cause JVM to create and throw an exception object, or the application code can do it. As soon as it happens, the control flow is transferred to the exception handling try
statement (also called a try-catch
or try-catch-finally
statement) if the exception was thrown inside a try
block. Here is an example of a caught exception:
void exceptionCaught(){ try { method2(); } catch (Exception ex){ ex.printStackTrace(); } } void method2(){ method1(null); } void method1(String s){ s.equals("whatever"); }
The method exceptionCaught()
calls method2()
which calls method1()
and passes to it null
. The line s.equals("whatever")
throws NullPointerException
which propagates through the method call stack until caught by the try-catch
block of the method exceptionCaught()
and its stack trace (which method called which method and in which line of the class) is printed:

From the stack trace, you can see that...