Common Java classes: Java exception mechanism, exception stack, exception handling method, exception chain, and exception loss

Source: Internet
Author: User
1. java standard exception Overview

Throwable indicates any class that can be thrown as an exception. It has two subclasses: Error and exception. From the source code of these two classes, we can see that these two classes do not add new methods, and throwable provides implementation of these methods. Error indicates the Compilation Time and system error. Exception is an exception class that can be thrown. Runtimeexception is inherited from exception (such as nullpointerexception), which indicates an exception during runtime and will be thrown automatically by JVM.

2. custom exception classes

Custom exception methods: Inherit throwable or exception. All the implementations of exception classes are implemented by the Base Class throwable. Therefore, you can refer to the exception and error classes to construct custom exception classes. We only need to add the constructor of the custom exception class.

Package demo. others; /*** custom exception class method ** 1. inherit throwable * 2. inherit exception ** @ author touch */public class myexceptiondemo extends exception {Private Static final long serialversionuid = 1l; public myexceptiondemo () {super ();} public myexceptiondemo (string message) {super (Message);} public myexceptiondemo (string message, throwable cause) {super (message, cause);} public myexceptiondemo (throwable cause) {super (cause );}}


 

3. Exception stack and Exception Handling Methods

You can use try and catch to catch exceptions. The caught exception. The following example demonstrates several common exception handling methods.

Package demo. others; import mine. util. exception. myexception; public class exceptiondemo1 {public void F () throws myexception {Throw new myexception ("custom exception");} public void g () throws myexception {f ();} public void H () throws myexception {try {G ();} catch (myexception E) {// 1. Obtain the element array in the stack trajectory to display the trajectory thrown by an exception for (stacktraceelement STE: E. getstacktrace () system. out. println (Ste. getmethodname (); // 2. Directly output the exception stack information to the standard error stream Or the standard output stream E. printstacktrace (); // output to standard error stream E. printstacktrace (system. err); E. printstacktrace (system. out); // 3. output the exception information to the file. // E. printstacktrace (New printstream ("file/exception.txt"); // 4. Throw an exception again. If an exception is thrown directly, the stack path is complete. If fillinstacktrace () is used () // The Origin of the exception will be taken from this method (currently H. // Throw E; throw (myexception) E. fillinstacktrace () ;}} public static void main (string [] ARGs) {try {New exceptiondemo1 (). H ();} catch (myexception e) {// todo auto-generated catch blocke. printstacktrace ();}}}

Running result:

F
G
H
Main
Mine. util. Exception. myexception: custom exception
At demo. Others. exceptiondemo1.f (exceptiondemo1.java: 7)
At demo. Others. exceptiondemo1.g (exceptiondemo1.java: 11)
At demo. Others. exceptiondemo1.h (exceptiondemo1.java: 16)
At demo. Others. exceptiondemo1.main (exceptiondemo1.java: 35)
Mine. util. Exception. myexception: custom exception
At demo. Others. exceptiondemo1.f (exceptiondemo1.java: 7)
At demo. Others. exceptiondemo1.g (exceptiondemo1.java: 11)
At demo. Others. exceptiondemo1.h (exceptiondemo1.java: 16)
At demo. Others. exceptiondemo1.main (exceptiondemo1.java: 35)
Mine. util. Exception. myexception: custom exception
At demo. Others. exceptiondemo1.f (exceptiondemo1.java: 7)
At demo. Others. exceptiondemo1.g (exceptiondemo1.java: 11)
At demo. Others. exceptiondemo1.h (exceptiondemo1.java: 16)
At demo. Others. exceptiondemo1.main (exceptiondemo1.java: 35)
Mine. util. Exception. myexception: custom exception
At demo. Others. exceptiondemo1.h (exceptiondemo1.java: 30)
At demo. Others. exceptiondemo1.main (exceptiondemo1.java: 35)

Analysis of the above program, first the main function is called, then the H function is called, then the G function, F function, F function throws an exception, and in the H function capture, at this time, the abnormal stack path will be output from the top of the stack to the bottom of the stack.

4. Exception chain

Sometimes we will catch an exception and then throw another exception, as shown in the following code:

Package demo. others; import Java. io. ioexception; import mine. util. exception. myexception; public class exceptiondemo2 {public void F () throws myexception {Throw new myexception ("custom exception");} public void g () throws exception {try {f ();} catch (myexception e) {e. printstacktrace (); throw new exception ("re-thrown exception 1") ;}} public void H () throws ioexception {try {G ();} catch (exception E) {// todo auto-generated catch blocke. printstacktrace (); throw new ioexception ("re-throw exception 2") ;}} public static void main (string [] ARGs) {try {New exceptiondemo2 (). H ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();}}}

Running result:

Mine. util. Exception. myexception: custom exception
At demo. Others. exceptiondemo2.f (exceptiondemo2.java: 9)
At demo. Others. exceptiondemo2.g (exceptiondemo2.java: 14)
At demo. Others. exceptiondemo2.h (exceptiondemo2.java: 23)
At demo. Others. exceptiondemo2.main (exceptiondemo2.java: 32)
Java. Lang. Exception: Re-throw exception 1
At demo. Others. exceptiondemo2.g (exceptiondemo2.java: 17)
At demo. Others. exceptiondemo2.h (exceptiondemo2.java: 23)
At demo. Others. exceptiondemo2.main (exceptiondemo2.java: 32)
Java. Io. ioexception: Re-throw exception 2
At demo. Others. exceptiondemo2.h (exceptiondemo2.java: 27)
At demo. Others. exceptiondemo2.main (exceptiondemo2.java: 32)

We can see from the results that the exception Stack has become smaller. That is to say, the original exception information is lost. How to save the most primitive exception information? The throwable class has a throwable cause attribute, indicating the original exception. The constructor that receives the cause parameter can pass the original exception to the new exception, or use the initcause () method. Example:

Package demo. others; import Java. io. ioexception; import mine. util. exception. myexception; public class exceptiondemo2 {public void F () throws myexception {Throw new myexception ("custom exception");} public void g () throws exception {try {f ();} catch (myexception e) {e. printstacktrace (); throw new exception ("re-throw exception 1", e) ;}} public void H () throws ioexception {try {G ();} catch (exception e) {// todo auto-generated catch blocke. printstacktrace (); ioexception IO = new ioexception ("re-throw exception 2"); Io. initcause (E); throw IO;} public static void main (string [] ARGs) {try {New exceptiondemo2 (). H ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();}}}


 

Result:

Mine. util. Exception. myexception: custom exception
At demo. Others. exceptiondemo2.f (exceptiondemo2.java: 9)
At demo. Others. exceptiondemo2.g (exceptiondemo2.java: 14)
At demo. Others. exceptiondemo2.h (exceptiondemo2.java: 23)
At demo. Others. exceptiondemo2.main (exceptiondemo2.java: 34)
Java. Lang. Exception: Re-throw exception 1
At demo. Others. exceptiondemo2.g (exceptiondemo2.java: 17)
At demo. Others. exceptiondemo2.h (exceptiondemo2.java: 23)
At demo. Others. exceptiondemo2.main (exceptiondemo2.java: 34)
Caused by: Mine. util. Exception. myexception: custom exception
At demo. Others. exceptiondemo2.f (exceptiondemo2.java: 9)
At demo. Others. exceptiondemo2.g (exceptiondemo2.java: 14)
... 2 more
Java. Io. ioexception: Re-throw exception 2
At demo. Others. exceptiondemo2.h (exceptiondemo2.java: 27)
At demo. Others. exceptiondemo2.main (exceptiondemo2.java: 34)
Caused by: Java. Lang. Exception: Re-throw exception 1
At demo. Others. exceptiondemo2.g (exceptiondemo2.java: 17)
At demo. Others. exceptiondemo2.h (exceptiondemo2.java: 23)
... 1 more
Caused by: Mine. util. Exception. myexception: custom exception
At demo. Others. exceptiondemo2.f (exceptiondemo2.java: 9)
At demo. Others. exceptiondemo2.g (exceptiondemo2.java: 14)
... 2 more

From the results, we can see that when we get "re-throw exception 2", we can also output the original exception "re-throw exception 1" and the original exception "custom exception, which is the exception chain.

5. Use of finally

The finally clause is always executed. It is usually used for cleaning, such as closing files and closing connections.

Here are several finally examples:

// Read the public static string read (string filepath) {stringbuilder STR = new stringbuilder (); bufferedreader in = NULL; try {In = new bufferedreader (New filereader (filepath); string s; try {While (S = in. readline ())! = NULL) Str. append (S + '\ n');} finally {In. close () ;}} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();} return Str. tostring ();}

Analysis: if an exception occurs when calling in = new bufferedreader (New filereader (filepath); an exception occurs, which indicates that the file path does not exist, that is, the file is not opened, at this time, the catch block will be skipped directly, instead of executing try... in. close (); you do not need to close the file.

Looking at another example will cause an exception or loss.

Package demo. others; import mine. util. exception. myexception; public class exceptiondemo3 {public void F () throws myexception {Throw new myexception ("exception 1");} public void g () throws myexception {Throw new myexception ("exception 2");} public static void main (string [] ARGs) {try {exceptiondemo3 EX = new exceptiondemo3 (); try {ex. F ();} finally {ex. G (); // catch the exception thrown by the G method at this time, and the exception thrown by the F method is lost} catch (myexception e) {system. out. println (e );}}}

Result: Mine. util. Exception. myexception: exception 2.

In this case, exception 1 is lost.
Or write as follows:

Package demo. others; import mine. util. exception. myexception; public class exceptiondemo3 {public void g () throws myexception {Throw new myexception ("exception 2");} public static void main (string [] ARGs) {exceptiondemo3 EX = new exceptiondemo3 (); try {ex. G () ;}finally {// direct return will be lost, so the thrown exception return ;}}}
6. Exception restrictions

(1) When overwriting a method, only the exceptions listed in the exception description of the base class method can be thrown. Some base class method declarations do not actually throw an exception, this is because an exception may be thrown in the override method of its subclass.

(2) The constructor can throw any exception without worrying about the exception thrown by the base class constructor. The exception description of the derived class constructor must include the exception description of the base class constructor, this is because the base class constructor is called to construct a derived class object. In addition, the derived class constructor cannot catch exceptions thrown by the base class constructor.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.