Chained Exceptions in JavaIn Java, a chained exception is a technique that enables programmers to associate one Exception with another. By providing additional information about a specific exception, debugging can be made easier. A chained exception is created by wrapping an existing exception in a new exception, which becomes the root cause of the new Exception. The new Exception can provide additional information, while the original Exception contains the actual error message and stack trace. It makes it easier to determine and fix the problem's source. Chained exceptions are especially useful when an exception is thrown due to another exception. In Java, a chained exception is created using one of the constructors of the exception class. Throwable ClassConstructors and methods for supporting chained exceptions are available in the Throwable class. Let's start by taking a look at the constructors. Throwable(Throwable cause): A Java constructor creates a new exception object with a specified cause exception. Throwable(String desc, Throwable cause): A Java constructor creates a new Throwable object with a message and a cause. It allows for chaining exceptions and providing more detailed information about errors. In Java, the following Throwable class methods enable chained exceptions: getCause(): It is a Java method of the Throwable class that returns the cause of the current Exception. It allows for accessing the Exception or error that triggered the current Exception to be thrown. initCause() method: determines the reason for the calling Exception. Example of Chained Exception:Filename: ChainedExceptionExample.java Output: Exception in thread "main" java.lang.RuntimeException: Exception at ChainedExceptionExample.main(ChainedExceptionExample.java:7) Caused by: Java.lang.NullPointerException: It is actual cause of the exception at ChainedExceptionExample.main(ChainedExceptionExample.java:8) Example of with and without chained ExceptionWithout Chained Exception:Filename: NonChainedExceptionExample.java Output: Enter a positive integer: -9 Invalid input: Number must be positive With Chained Exception:Filename: ChainedExceptionExample.java Output: Enter a positive integer: -9 Exception in thread "main" java.lang.RuntimeException: Invalid input at ChainedExceptionExample.main(ChainedExceptionExample.java:17) Caused by: Java.lang.IllegalArgumentException: Number must be positive at ChainedExceptionExample.main(ChainedExceptionExample.java:11) Difference Between non chained and chained Exception
Next TopicFinal static variable in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India