Java Reference
In-Depth Information
Here is the sequence of events that occurs when method3 executes:
1. “Inside method3” displays and x and y are initialized.
2. Flow of control enters the try block on line 15, and line 16 causes an
ArithmeticException to be thrown.
3. The JVM searches the associated catch clauses for one that catches an
ArithmeticException , which line 18 does. Flow of control jumps to line 18.
(Line 17 does not execute.)
4. The catch block executes, displaying an error message.
5. Because the exception was handled, execution resumes as normal. method3 finishes
successfully and is popped off the method call stack. The remaining methods
complete successfully, and the output is
Inside main
Inside method1
Inside method2
Inside method3
Something went wrong: / by zero
End of main
Because the exception was handled, the program did not terminate prematurely, as
shown by the display of End of main .
The Throwable Class
The java.lang.Throwable class is the parent class of all objects that can be thrown
(either by the JVM or by using the throw keyword). Only objects of type Throwable or
subclasses of Throwable can appear in a catch clause.
When you catch an exception, a common task is to display the stack trace or log it to a
fi le. The following methods defi ned in Throwable provide information about the stack
trace and the exception thrown:
public void printStackTrace()
This method prints the stack trace to System.err .
public void printStackTrace(PrintStream s)
This method prints the stack trace to the specifi ed PrintStream .
public void printStackTrace(PrintWriter s)
This method prints the stack trace to the specifi ed PrintWriter .
Search WWH ::




Custom Search