Exceptions handling
Custom exception classes
Use exception chaining
How to use exception chaining
- Exception chaining lets you maintain exception information for exceptions that are caught when new exceptions are thrown.
- Exception chaining uses the cause field, which represents the original exception that caused the current exception to be thrown.
- You can set the cause of an exception via the exception's constructor or by using the initCause method.
- You can retrieve an exception's cause by using the getCause method.
Constructors and methods of the Throwable class for exception chaining
Constructor | Description |
---|---|
Throwable(cause) | Creates a new exception with the specified exception object as its cause. |
Throwable(message, cause) | Creates a new exception with the specified message and cause. |
Method | Description |
---|---|
getCause() | Returns the exception object that represents this exception's cause. |
initCause(cause) | Sets the exception's cause to the specified exception. Can be called only once. If you initialize the cause via the constructor, you can't call this method at all. |
A custom exception class that uses exception chaining
public class ProductDAOException extends Exception { public ProductDAOException() { } public ProductDAOException(Throwable cause) { super(cause); } }
Code that throws ProductDAOException with chaining
catch (IOException e) { throw new ProductDAOException(e); }
Code that catches ProductDAOException and displays the cause
catch (ProductDAOException e) { System.out.println( "A ProductDAOException has occurred."); System.out.println(e.getCause().toString()); }
Resulting output
A ProductDAOException has occurred. java.io.IOException: IOException