Chained Exceptions allows to relate one exception with another exception, i.e one exception describes cause of another exception. For example, consider a situation in which a method throws an ArithmeticException because of an attempt to divide by zero but the actual cause of exception was an I/O error which caused the divisor to be zero. The method will throw only ArithmeticException to the caller. So the caller would not come to know about the actual cause of exception. Chained Exception is used in such type of situations.
Constructors Of Throwable class Which support chained exceptions in java :
- Throwable(Throwable cause) :- Where cause is the exception that causes the current exception.
- Throwable(String msg, Throwable cause) :- Where msg is the exception message and cause is the exception that causes the current exception.
Methods Of Throwable class Which support chained exceptions in java :
- getCause() method :- This method returns actual cause of an exception.
- initCause(Throwable cause) method :- This method sets the cause for the calling exception.
Example of using Chained Exception:
java.lang.NumberFormatException: Exception java.lang.NullPointerException: This is actual cause of the exception
This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Exceptions in Java
- Errors V/s Exceptions In Java
- Built-in Exceptions in Java with examples
- Checked vs Unchecked Exceptions in Java
- Using throw, catch and instanceof to handle Exceptions in Java
- Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java
- Java.util.concurrent.RecursiveAction class in Java with Examples
- Java lang.Long.numberOfLeadingZeros() method in Java with Examples
- Java lang.Long.highestOneBit() method in Java with Examples
- Java.util.concurrent.Phaser class in Java with Examples
- Java lang.Long.byteValue() method in Java with Examples
- Java.util.Collections.rotate() Method in Java with Examples
- Java lang.Long.lowestOneBit() method in Java with Examples
- Java lang.Long.numberOfTrailingZeros() method in Java with Examples
- Java.util.LinkedList.offer(), offerFirst(), offerLast() in Java