java--Exception (iii)

Source: Internet
Author: User

The problem is introduced in the following test code:

ImportJava.io.*; Public classhideexception {//one function reads two files at a time Public voidReadtwofile ()throwsFileNotFoundException, ioexception{bufferedreader br1=NULL; BufferedReader Br2=NULL; FileReader FR=NULL; Try{FR=NewFileReader ("A.txt");//1BR1=NewBufferedReader (FR); intCount = Br1.read ();//2//process Code1 ....FR=NewFileReader ("B.txt");//3Br2=NewBufferedReader (FR); Count= Br2.read ();//4//Process Code2    }finally{        if(BR1! =NULL) Br1.close (); //5        if(Br2! =NULL) Br2.close (); //6    }}//Test Client Public Static voidMain (string[] args) {hideexception He=Newhideexception (); Try{he.readtwofile (); } Catch(FileNotFoundException e) {//...e.printstacktrace ();//7    } Catch(IOException e) {//...e.printstacktrace ();//8    }}}
Source Code

As shown in code Snippet 3, Readtwofile is used to read two files. Where statements//1 and statements//3 may throw filenotfoundexception, statements//2,//4,//5,//6 may throw IOException. By performing a logical analysis of the control flow, the finally clause in the above code will be executed anyway. what/which statements in the main function are executed when the//3 and//5 occur simultaneously?

The answer is: when//3 produces a filenotfoundexception , the flow of control is shifted to the finally clause, but//5 IOExceptionagain, Then this time back to the main caller will be IOException instead of filenotfoundexception. because the exception generated by the//3 is covered by the exception thrown by the//5 . To do this, the statement //8in the main function is executed.

Focus : A function that throws multiple exceptions, but only one exception can be propagated to the calling side.

Remember: The last exception thrown is the only exception that is received by the caller, and all other exceptions are swallowed up and masked. If the caller wants to know the initial cause of the failure, there is no way to hide any exceptions in the program.

I. Self-defined exception encapsulation class

The problem is that the exception is abandoned. For this reason, a simple idea is that we need to save the exception that was "discarded" during the execution of the function. One solution is to define a list that contains all the exceptions. An exception is thrown at the end of the function that includes all of the above exceptions. In this way, we can ensure that there is no "discard" phenomenon.

  

The first step: define a custom exception wrapper class that contains all the thrown exceptions. As shown in the following code:

Code Snippet 1

  

The customexception exception is just an exception set that can hold multiple exceptions, but it is not a real exception in itself, it is just to solve the problem of throwing multiple exceptions at once.

Step Two: transform the business code to solve the problem of "discarding" the exception. Set up a container that can throw multiple exceptions, and then add the exception to the container at the point where the exception can be thrown. As shown in code Snippet 2.

Code Snippet 2

  

 Public classhideexception {//Custom Exception Classes    classCustomeexceptionextendsException {//omitted here, see Code Snippet 1    }    //one function reads two files at a time     Public voidReadtwofile ()throwscustomeexception {BufferedReader BR1=NULL; BufferedReader Br2=NULL; FileReader FR=NULL; List<Throwable> list =NewArraylist<throwable>(); Try{FR=NewFileReader ("A.txt");//1BR1=NewBufferedReader (FR); intCount = Br1.read ();//2//process Code1 ....FR=NewFileReader ("B.txt");//3Br2=NewBufferedReader (FR); Count= Br2.read ();//4//Process Code2        } Catch(FileNotFoundException ffe) {list.add (FFE);//Prevent drop Exceptions        } Catch(IOException IE) {list.add (IE);//Prevent drop Exceptions        } finally {            if(BR1! =NULL) {                Try{br1.close (); } Catch(IOException IE) {list.add (IE);//Prevent drop Exceptions                }            }            if(Br2! =NULL) {                Try{br2.close (); } Catch(IOException IE) {list.add (IE);//Prevent drop Exceptions                }            }        }        //Check the number of exceptions        if(List.size () > 0)            Throw Newcustomeexception (list); }    //Test Client     Public Static voidMain (string[] args) {hideexception He=Newhideexception (); Try{he.readtwofile (); } Catch(customeexception CE) {//Exception handling Code// ......        }    }}
Business code

The appeal code adds each exception to an exception set, resolves the exception drop exception, and can also centralize the exception.

Second, the abnormal chain

  definition: code consists of a layer of function calls. If a function throws an exception, one method is to resolve it in-place, and one method is to call the throw method to throw the exception to the upper calling function, so that the upper calling function can still call the throw method again to continue to throw the exception of the method, thus creating an exception chain consisting of an exception.

  Why: for some exceptions if you take an in-place solution, you will let the upper calling function do not know what caused the program exception, for this reason it is not easy to troubleshoot the program or user operation feedback. For this reason, it is necessary to pass the layer of the abnormal chain, and finally let the function with corresponding processing responsibility handle the exception.

Exception chain implementation exception pass the following code:

 Public classExceptionchaintest {classCustomeexceptionextendsException {//1 Empty Constructors         Publiccustomeexception () {Super(); }        //2 Defining the cause of an exception         Publiccustomeexception (String message) {Super(message); }        //3 Define the cause of the exception and retain the original information         Publiccustomeexception (String message, throwable cause) {Super(message, cause); }        //4 preserving Original information         Publiccustomeexception (Throwable cause) {Super(cause); }    }    //The underlying test function     Public voidFunc2 ()throwsException {Throw NewException ("Func2 Exception ..."); }    //Upper test function     Public voidFunc1 ()throwsException {Try{Func2 (); } Catch(Exception ex) {Throw NewCustomeexception ("func1 exception");//5        }    }    //Client test function     Public Static voidMain (string[] args) {exceptionchaintest test=Newexceptionchaintest (); Try{test.func1 (); } Catch(Exception e) {e.printstacktrace (); }    }}

The first step: We first customize an exception class: Customeexception. The method of//3 and//4 in this constructor is the core of the implementation of the exception chain, that is, the original exception information is preserved.

In the second step, we simulate an example to illustrate how to implement the exception chain transfer, the function call chain is: main function->func1 function->func1 function. According to the execution logic, the FUNC2 () function throws a exception type exception to the upper Func1 (), and the func1 () function does not handle the exception specifically, but rebuilds an exception object and throws it to the main function.

Let's think about it for a minute and figure out what the message will be:

    

Think the information above is not a little bit less what? Yes, the original cause of the anomaly was discarded. What can the old iron do to solve it?

The way to solve the problem is also very simple, that is, the code snippet in the //5

throw new Customeexception ("Func1 exception");//5

To be replaced by:

throw new customeexception ("Func1 exception", ex); //6

After the replacement, the program runs as follows:

    

Ok! The world is back to a state of harmony, and from the thrown exception we find the most primitive cause of the anomaly. Note that the original exception information is missing from the code snippet //5 , and the modified //6 is the true exception encapsulation, preserving the original exception information.

Important: after the upper calling function catches an exception, it can be encapsulated (as in the example above in 3, 4 constructors) and then thrown so that the exception information obtained by the subsequent call function is not lost and the root cause of the exception is obtained so that the programmer can solve the problem or feedback to the user.

Third, summary
    1. Exceptions need to be encapsulated and passed, treat exceptions, we do not "devour" the exception, do not directly throw an exception, you can take an exception container for the execution of the code thrown during the collection of exceptions, and finally feedback to the caller, so that the exception is not discarded, so that users get the root cause of the exception. This technique is commonly used in situations where a function may throw multiple exceptions.

    2. The anomaly chain is also a practical method for passing exceptions, which is often used in business scenarios with a certain function call depth.

This article comes from the public number- programmer Chatbook

     

java--Exception (iii)

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.