Exceptions handling
Exceptions
Throwable class
Common constructors of the Throwable class
Constructor | Description |
---|---|
Throwable() | Creates a new exception with a null message. |
Throwable(message) | Creates a new exception with the specified message. |
Common methods of the Throwable class
Method | Description |
---|---|
getMessage() | Returns the message associated with the exception, if one is available. |
printStackTrace() | Prints the stack trace to the standard error output stream along with the value of the toString method of the exception object. |
printStackTrace(PrintWriter stream) | Prints the stack trace showing the sequence of method calls when an exception occurs. Output is sent to the stream specified by the parameter stream. |
toString() | Returns a string that includes the name of the class that the exception was created from, along with the message associated with the exception, if one is available. |
Code that throws an exception with a message
try { throw new IOException("An IO error has occurred."); } catch (IOException e) { System.err.println(e.getMessage()); System.err.println(e.toString()); }
Resulting output
An IO error has occurred. java.io.IOException: An IO error has occurred.
Code that uses the printStackTrace method
try { throw new IOException("An IO error has occurred."); } catch (IOException e) { e.printStackTrace(); } }
Resulting output
java.io.IOException: An IO error has occurred. at ProductTestApp.getProductData(ProductTestApp.java:14) at ProductTestApp.main(ProductTestApp.java:7)
Code that uses the printStackTrace method
import java.io.*; public class PrintStackTraceExample1 { public static void main(String[] args) { try { methodA(); } catch (Exception e) { System.out.println(e.toString() + " caught in main"); e.printStackTrace(); } } public static void methodA() throws Exception { methodB(); } public static void methodB() throws Exception { methodC(); } public static void methodC() throws Exception { throw new Exception("Exception generated " + "in method C"); } }
Resulting output
java.lang.Exception: Exception generated in method C caught in main java.lang.Exception: Exception generated in method C at PrintStackTraceExample1.methodC (PrintStackTraceExample1.java:30) at PrintStackTraceExample1.methodB (PrintStackTraceExample1.java:25) at PrintStackTraceExample1.methodA (PrintStackTraceExample1.java:20) at PrintStackTraceExample1.main (PrintStackTraceExample1.java:9)