Saturday, February 17, 2018

Chained Exceptions


Adapted from:
https://docs.oracle.com/javase/tutorial/essential/exceptions/chained.html
http://www.baeldung.com/java-chained-exceptions
https://stackoverflow.com/questions/5020876/what-is-the-advantage-of-chained-exceptions

An application often responds to an exception by throwing another exception. In effect, the first exception causes the second exception. It can be very helpful to know when one exception causes another. Chained Exceptions help the programmer do this.
The following are the methods and constructors in Throwable that support chained exceptions.

 Throwable Class

Throwable class has some constructors and methods to support chained exceptions. Firstly, let’s look at the constructors.
  • Throwable(Throwable cause) – Throwable has a single parameter, which specifies the actual cause of an Exception.
  • Throwable(String desc, Throwable cause) – this constructor accepts an Exception description with the actual cause of an Exception as well.
  • getCause() method  This method returns the actual cause associated with current Exception.
  • initCause() method – It sets an underlying cause with invoking Exception.
The Throwable argument to initCause and the Throwable constructors is the exception that caused the current exception. getCause returns the exception that caused the current exception, and initCause sets the current exception's cause.
The following example shows how to use a chained exception.

try {

} catch (IOException e) {
    throw new SampleException("Other IOException", e);
}


Exception chaining allows you to map one exception type to another, so that a method can throw exceptions defined at the same abstraction level as the method itself, without discarding important debugging information.

We need to chain the exceptions to make logs readable. => https://stackoverflow.com/questions/5020876/what-is-the-advantage-of-chained-exceptions








No comments:

Post a Comment

java special for collection size, array size, and string size

Size: For Collections (eg: Map, List, etc ): usually it use collection.size(), eg         Map<Character, Integer> map ...