Chained Exceptions were introduced in Java with JDK 1.4. In Chained exceptions, we can associate an exception with some other exception so that it can be inferred that occurrence of one exception is due to associated exception in reality.
This program clearly shows the concept.
This program clearly shows the concept.
package ExceptionIllustration; class ChainDemo { static void DemoProc() { NullPointerException e = new NullPointerException("Top Layer"); e.initCause(new ArithmeticException("Cause")); throw e; } public static void main(String...args) { try { DemoProc(); } catch(NullPointerException e) { System.out.println("Caught " + e); System.out.println("Original Cause " + e.getCause()); } } }In the program, we can see that the NullPointerException has been associated with Arithmetic Exception such that root cause of NullPointerException is Arithmetic Exception. To compile the program.
javac -d . ChainDemo.javaAnd to run the program
java ExceptionIllustration.ChainDemoHere is the sample output that I got.
Caught java.lang.NullPointerException: Top Layer Original Cause java.lang.ArithmeticException: Cause
No comments:
Post a Comment