Thinking in Java---exception handling mechanism

Source: Internet
Author: User
Tags throw exception throwable

Java's exception handling mechanism can make the program have excellent fault tolerance and make the program more robust. The so-called exception is the problem that prevents the current method or scope from continuing to execute, and when the program runs with an exception, The system automatically generates a exception object to notify the program. This greatly simplifies our work.
Of course, Java has many kinds of exception objects, the following picture shows the Java Exception class inheritance system.

From the picture you can see that Java divides all the anomalies into two types: exceptions (Exception) and errors (error), both of which inherit the Throwable parent class. Error errors generally refer to problems related to virtual machines, such as system crashes, Virtual machine errors, and so on. This error cannot be recovered or is not captured, will cause the application to break, usually the application cannot handle these errors, and therefore should not attempt to capture with catch. For exception we can capture and process the exception handling mechanism. .

I. General format for exception handling

        try{            ///可能会抛出异常的代码        }        catch(Type1 id1){            //处理Type1类型异常的代码        }        catch(Type2 id2){            ///处理type2类型异常的代码        }

Put code in the try block that might have an exception (but we don't know what kind of exception it is). If an exception occurs, the try block throws the system auto-generated exception object, and the exception handling mechanism will be responsible for searching for the first handler that matches the exception type and then executing the catch statement ( Will not be looked down). It looks similar to the switch statement. In addition to the exception classes listed above, we can define exceptions ourselves and then process them. Defining exceptions the most important thing is the name of the exception class, It is better to be well-known and to know righteousness. In addition, the throws and throw that are often present in exception handling are two keywords; throws means that the current program does not handle this exception and throws it to the top-level program that invokes the program, if it is main () Method is passed to the JVM virtual machine processing. The throw represents an explicit throw of an exception object. The following code uses the knowledge points mentioned above.

///   Define a simple exception class yourself, just declare the following inheritance relationship///   You can also write the constructor yourself, but this is not necessary Public classSimpleexception extends exception{ ///public simpleexception ();     //Public simpleexception (String str) {     //Super (STR)};}package Lkl;import Java.util.Scanner; Public classexceptiontest {///   declares that the program does not handle simpleexception exceptions but throws them out       Public void F() throws simpleexception{System. out. println ("Throws simpleexception from F ()");///   throw out a Simpleexception exception object            Throw NewSimpleexception (); }/////   Multiple try statements are executed sequentially, even if an exception occurs on the previous try statement, the next try statement will still execute       Public Static void Main(string[] args) {Exceptiontest et =NewExceptiontest ();Try{ET.F (); }///   handle simpleexception exception thrown in try          Catch(Simpleexception sn) {System. out. println ("Catch It");//Call the Printstacktrace () method of the Exception class, which is printed to the standard error stream by default              ///   Now we display the specified output to the standard output stream              ////   will print the method call sequence from the method call until the exception is thrown, the top of the stack is the last call and the bottom of the stack is the first time it is dropped.Sn.printstacktrace (System. out); }Try{int[] A=New int[Ten]; Scanner sc =NewScanner (System.inch); System. out. println ("Please enter K:");intK=sc.nextint ();              Sc.close (); System. out. println (A[k]); }///   handle exception for array subscript out of bounds          Catch(ArrayIndexOutOfBoundsException AE) {System. out. println ("Catch arrayindexoutofboundsexception"); Ae.printstacktrace (System. out); }      }}

Two. Print exception information
The base class of the exception class, exception, provides a set of methods to obtain some information about an exception. So if we get an exception object, then we can print out some useful information, the most common is void printstacktrace () This method, This method returns an array of elements in the stack trajectory, each of which represents a frame in the stack. Element 0 is the top element of the stack and is the last method call in the call sequence (where the exception was created and thrown); He has several different overloaded versions, You can output information to a different stream. The following code shows how to print the basic exception information:

Package LKL;///   The common method of testing anomaly class exception Public classExceptionmethods { Public Static void Main(string[] args) {Try{Throw NewException ("My Exception"); }///////   by capturing the base class of the exception class exception to catch all types of exceptions        Catch(Exception e) {System. out. println ("Caught Exception"); System. out. println ("GetMessage ():"+e.getmessage ()); System. out. println ("Getlocalizedmessage ():"+e.getlocalizedmessage ()); System. out. println ("toString ():"+e.tostring ()); System. out. println ("Printstacktrace ():"); E.printstacktrace (System. out); }    }}

Three. Re-throw exception and exception chain
Sometimes it is necessary to re-throw the caught exception, which is syntactically simple. But the problem is that if thrown directly, the information in the exception object will still be the information in the original exception object. If we want to keep this information new, we can call the Fillinstacktrace () method, This method returns a Throwable object, which is obtained by filling in the current call stack information into the original object. Calling Fillstacktrace () is the new occurrence of the exception. If we throw another exception after catching the exception, Then the information of the original anomaly will be lost, and the same method as Fillinstacktrace () is obtained.
The so-called anomaly chain refers to throwing another exception after catching an exception and hoping to preserve the information of the original exception. The Throwable subclass in Java can accept a cause object as a parameter in the constructor. This parameter is actually the original exception object, This allows the exception chain to be traced to the location where the exception originated by passing the original exception to the new exception, even if a new exception is created and thrown at the current location. But in Throwable subclasses, only error,exception, RuntimeException These three subclasses provide a constructor with a cause factor, and if you want to link other types of exceptions, you should use the Initcause () method instead of the constructor.

Four. Use finally to clean up
The reason for introducing the finally statement is that we want some code to always be executed, regardless of whether an exception is thrown in the try block. The basic format for exception handling becomes the following:

     try{            ///可能会抛出异常的代码        }        catch(Type1 id1){            //处理Type1类型异常的代码        }        catch(Type2 id2){            ///处理type2类型异常的代码        }        finally{            ///总是会执行的代码        }

In fact, catch and finally statements can also be only one occurrence. The following code shows that the finally statement always runs

 PackageLKL; Public  class finallytest extends Exception{     Public Static intCount=0; Public Static void Main(string[] args) { while(true){Try{//Whether it is throwing an exception, the finally statement will execute                if(count++==0){Throw NewMyException (); } System.out.println ("No Exception"); }Catch(MyException me) {System.out.println ("MyException"); }finally{System.out.println ("in finally clause");if(count==2) Break; }        }    }}

The following code shows that even if there is a return statement in the try, the finally statement will still be executed, and it looks like there are multiple return points.

Package LKL; Public classMultiplereturns { Public Static void F(inti) {System. out. println ("Initialization that requires cleanup");Try{///   before the function reutrn, the finally returns the first executionSystem. out. println ("point 1");if(i==1)return; System. out. println ("point 2");if(i==2)return; System. out. println ("point 3");if(i==3)return; System. out. println ("point 4");if(i==4)return; }///   before the above return, the finally statement is executed first        finally{System. out. println ("perferming cleanup"); }    } Public Static void Main(string[] args) { for(intI=1; i<=4; i++) F (i); }}

So what do you always do with the finally statement? In Java we are primarily used to clean up resources other than memory, including: Open files or network connections, images drawn on the screen, etc.

Five. Exception handling and inheritance
The last question is about exception handling and inheritance. When exception handling and inheritance occur together, the problem that we need to focus on is that the parent class constructor throws an exception and the subclass constructor throws an exception, and in the subclass overrides the problem of how the parent class method declares the exception. In fact, there are two rules:
1). Subclasses overriding the base class method throws an exception that must be no larger than the exception type thrown by the original base class method.
2). Although syntax is not specified for the exception declaration of the subclass constructor, the exception description of the child class constructor must include the exception description of the base class constructor. (because the constructor of the base class is always called).
This is demonstrated in the following code:

 Public  class foul extends baseballexception{} Public  class Popfoul extends foul{} Public  class baseballexception extends Exception{} Public  class Strike extends baseballexception{} Public  class rainedout extends stormexception{} Public  interface Storm {     Public void Event()throwsRainedout; Public void Rainhard()throwsRainedout;} Public Abstract  class inning {     Public inning()throwsbaseballexception{}/// definition throws an exception, but there is actually no     Public void Event()throwsbaseballexception{};//Declaration throws two exceptions     Public Abstract void AtBat()throwsStrike, foul; Public void Walk() {}} Public  class stormyinning extends inning implements Storm {     Public stormyinning()throwsbaseballexception,rainedout{} Public stormyinning(String s)throwsfoul,baseballexception{}///Because the base class method does not throw an exception and the subclass-overridden method throws the    /// so compile error   //void Walk () throws popfoul{}    //interfaces Cannot add exception types to base class methods    //public void Event () throws rainedout{}    ///The overridden method throws the same exception as the base class method is possible     Public void Rainhard()throwsrainedout{}The //base class method throws an exception, and the overridden method does not throw it .     Public void Event() {}//overridden method throws the subclass of the base class exception is also possible     Public void AtBat()throwspopfoul{} Public Static void Main(string[] args) {Try{/// The rainedout,baseballexception exception may be thrown in the constructor in the following two lines of code            The ///atbat () method may throw a Popfoul exception. So there are three kinds of exceptions to deal with.Stormyinning si =NewStormyinning ();        Si.atbat (); }Catch(Popfoul e) {System.out.println ("Pop Foul"); }Catch(Rainedout e) {System.out.println ("Rained out"); }Catch(Baseballexception e) {System.out.println ("Generic Baseball"); }Try{//This code has been transformed upward, so the above three cases are handled outside            ////must also handle strike exceptions thrown by the base class Atbat () methodinning i =NewStormyinning ();        I.atbat (); }Catch(Strike e) {System.out.println ("Strike"); }Catch(Popfoul e) {System.out.println ("Pop Foul"); }Catch(Rainedout e) {System.out.println ("Rained out"); }Catch(Baseballexception e) {System.out.println ("Generic Baseball"); }    }}

Thinking in Java---exception handling mechanism

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.