Case of abnormal loss:
Define three exceptions first:
Public classExceptionaextendsException { PublicExceptiona (String str) {Super(); }} Public classExceptionbextendsExceptiona { Publicexceptionb (String str) {Super(str); }} Public classExceptioncextendsExceptiona { Publicexceptionc (String str) {Super(str); }}
Then define a test class:
Public classNevercaught {Static voidF ()throwsexceptionb{Throw NewEXCEPTIONB ("Exception B"); } Static voidG ()throwsExceptionc {Try{f (); } Catch(exceptionb e) {exceptionc C=NewExceptionc ("Exception a"); ThrowC; } } Public Static voidMain (string[] args) {Try{g (); } Catch(Exceptionc e) {e.printstacktrace (); } } }
Results of the output:
exception. Exceptionc
At exception. NEVERCAUGHT.G (Nevercaught.java:12)
At exception. Nevercaught.main (nevercaught.java:19)
The EXCEPTIONB information was lost in the printed exception message. If you want to be able to output exceptionb and exceptionc information at the same time, you need to use an exception chain.
The main function of the exception chain is to save the exception information, while throwing another exception without losing the original exception.
The following code implements an exception chain up-throws an exception in two ways.
Public classNevercaught {Static voidF ()throwsexceptionb{Throw NewEXCEPTIONB ("Exception B"); } Static voidG ()throwsExceptionc {Try{f (); } Catch(exceptionb e) {exceptionc C=NewExceptionc ("Exception a"); //Exception ChainC.initcause (e); //another way to achieve this//throw new Exception ("Exception a", e); ThrowC; } } Public Static voidMain (string[] args) {Try{g (); } Catch(Exceptionc e) {e.printstacktrace (); } } }
It is important to note that:
Only Error,exception,runimeexception provides a constructor with the cause parameter, and so the exception is set cause only by Initcause (). When you define an exception that provides a constructor with the cause parameter, it can also be set normally.
Java exception loss and exception chaining