Thinking in Java---exception handling mechanism

Source: Internet
Author: User

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 run, and when the program runs with an exception, The system will voluntarily generate a exception object to notify the program. This greatly simplifies our work.
Of course, Java has a very large number of exception objects, the following image 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 usually refer to problems related to virtual machines, such as system crashes, Virtual machine errors, and so on. Such errors cannot be recovered or are not captured, causing the application to break and usually the application cannot handle these errors. Therefore, you should not attempt to capture with catch. For exception we are able to capture and process. The following is an introduction to the exception handling mechanism from several aspects.

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 the exception is in detail). Assuming that the exception occurred, the try block throws the system's own generated exception object, and the exception handling mechanism will be responsible for searching the first handler that matches the exception type and then running the Catch statement ( Not looking down). It looks similar to the switch statement. In addition to the exception classes listed above, in fact we are able to customize exceptions 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, assuming 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.

///   to customize a simple exception class, simply declare the following inheritance relationship///   can also write the constructor itself, 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 run sequentially, even if an exception occurs in the previous try statement, the next try statement will still run       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 get some information about the exception. So suppose we get an exception object, then we can print out some useful information, most often using the void Printstacktrace () 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 version numbers, The ability to output information to a different stream. The following code shows how to print the main exception information:

Package LKL;///   Test anomaly Class exception regular usage 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. Another throw exception and exception chain
Sometimes it is necessary to throw the caught exception again, which is syntactically easy. But the problem is that the information in the exception object will still be the information in the original exception object if it is thrown directly. Let's say 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. The line that calls Fillstacktrace () is the new occurrence of the exception. Suppose we throw a second exception after catching an 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 the exception that is thrown after catching an exception, and wants to preserve the information of the original exception. The Throwable subclass in Java can accept a cause object as a parameter in the constructor. The parameter is actually the original exception object, By passing the original exception to the new exception, the new exception is created and thrown even at the current location, and the exception chain can be traced to the location where the exception originally occurred. But in Throwable's subclasses, only the error,exception, RuntimeException These three subclasses provide a constructor with a cause factor, assuming that 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 run, 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 only have one appearance. 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 or not to throw an exception, the finally statement will run                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 run 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 function reutrn, finally run back firstSystem. 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 run first        finally{System. out. println ("perferming cleanup"); }    } Public Static void Main(string[] args) { for(intI=1; i<=4; i++) F (i); }}

So what are the finally statements that always run?

In Java we are primarily used to clean up other resources except memory, which include: Files that have been opened or network connections, images drawn on the screen, and so on.

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. To summarize, in fact, 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 there is no syntax for the exception declaration of a child class constructor, the exception description of the subclass constructor must contain 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 no exception is thrown in the base class method 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 can be     Public void Rainhard()throwsrainedout{}The //base class method throws an exception, and the overridden method does not throw it .     Public void Event() {}//overridden method that 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 anomalies 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.