
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Chained Exception in Java
Chained exception helps to relate one exception to other. Often we need to throw a custom exception and want to keep the details of an original exception that in such scenarios we can use the chained exception mechanism. Consider the following example, where we are throwing a custom exception while keeping the message of the original exception.
Example
public class Tester { public static void main(String[] args) { try { test(); }catch(ApplicationException e) { System.out.println(e.getMessage()); } } public static void test() throws ApplicationException { try { int a = 0; int b = 1; System.out.println(b/a); }catch(Exception e) { throw new ApplicationException(e); } } } class ApplicationException extends Exception { public ApplicationException(Exception e) { super(e); } }
Output
java.lang.ArithmeticException: / by zero
The throwable class supports chained exception using the following methods:
Constructors
Throwable(Throwable cause) - the cause is the current exception.
Throwable(String msg, Throwable cause) - msg is the exception message, the cause is the current exception.
Methods
getCause - returns actual cause.
initCause(Throwable cause) - sets the cause for calling an exception.
Advertisements