- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 Javan
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.
- Related Articles
- What are chained exceptions in Java?
- Chained Exceptions in C#
- Exception propagation in Java
- Exception chaining in Java
- Creating a chained operation class in JavaScript
- Exception propagation in Java programming
- How to create a user defined exception (custom exception) in java?
- Null Pointer Exception in Java Programming
- Exception Handling in C++ vs Java
- What is exception propagation in Java?
- Is it possible to throw exception without using "throws Exception" in java?
- While chaining, can we throw unchecked exception from a checked exception in java?
- Out of memory exception in Java:\n
- Exception handling with method overriding in Java.
- Difference between Exception and Error in Java

Advertisements