The developer's response to exception handling try-catch-finally Statement blocks are familiar . If in try Exception thrown in statement block , Before control is transferred to a layer of code on the call stack ,finally Statements in the statement block will also execute . however finally The statement block is in the process of execution , An exception may also be thrown . If finally The statement block also throws an exception , So this exception will pass up , Before try The exception in the statement block is lost . For example :

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package  test;
 
public  class  DisappearedException {
     public  void  show()  throws  BaseException {
         try  {
             Integer.parseInt( "Hello" );
         catch  (NumberFormatException e1) {
             throw  new  BaseException(e1);
         finally  {
             try  {
                 int  result =  2  0 ;
             catch  (ArithmeticException e2) {
                 throw  new  BaseException(e2);
             }
         }
     }
     public  static  void  main(String[] args)  throws  Exception {
         DisappearedException d =  new  DisappearedException();
         d.show();
     }
}
 
class  BaseException  extends  Exception {
     public  BaseException(Exception ex){
         super (ex);
     }
     private  static  final  long  serialVersionUID = 3987852541476867869L;
}

On this issue There are generally two solutions : One is to throw try The original exception generated in the statement block , Ignore in finally Exception generated in statement block . The starting point is try The exception in the statement block is the root of the problem . For example :

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package  test;
 
import  java.io.FileInputStream;
import  java.io.IOException;
 
public  class  ReadFile {
     public  static  void  main(String[] args) {
         ReadFile rf =  new  ReadFile();
         try  {
             rf.read( "F:/manifest_provider_loophole.txt" );
         catch  (BaseException2 e) {
             e.printStackTrace();
         }
     }
     public  void  read(String filename)  throws  BaseException2 {
         FileInputStream input =  null ;
         IOException readException =  null ;
         try  {
             input =  new  FileInputStream(filename);
         catch  (IOException ex) {
             readException = ex;
         finally  {
             if (input !=  null ){
                 try  {
                     input.close();
                 catch  (IOException ex2) {
                     if (readException ==  null ){
                         readException = ex2;
                     }
                 }
             }
             if (readException !=  null ){
                 throw  new  BaseException2(readException); 
             }
         }
     }
}
 
class  BaseException2  extends  Exception {
     private  static  final  long  serialVersionUID = 5062456327806414216L;
     public  BaseException2(Exception ex){
         super (ex);
     }
}

The other is to record all the exceptions . The advantage of this is that you don't lose any exceptions . stay java7 Before , You need to implement your own exception class , And in the java7 in , Have been to Throwable Class has been modified to support this . stay java7 In Chinese, it means Throwable Class to increase addSuppressed Method . When an exception is thrown , There may be other exceptions that are suppressed by the exception , So it can't be thrown normally . You can pass addSuppressed Methods record these suppressed methods . The suppressed exception will appear in the stack information of the thrown exception , It can also be done through getSuppressed Method To get these exceptions . The advantage of doing so is not to lose any exceptions , Convenient for developers to debug . For example :

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package  test;
 
import  java.io.FileInputStream;
import  java.io.IOException;
 
public  class  ReadFile2 {
     public  static  void  main(String[] args) {
         ReadFile rf =  new  ReadFile();
         try  {
             rf.read( "F:/manifest_provider_loophole.txt" );
         catch  (BaseException2 e) {
             e.printStackTrace();
         }
     }
     public  void  read(String filename)  throws  IOException {
         FileInputStream input =  null ;
         IOException readException =  null ;
         try  {
             input =  new  FileInputStream(filename);
         catch  (IOException ex) {
             readException = ex;
         finally  {
             if (input !=  null ){
                 try  {
                     input.close();
                 catch  (IOException ex2) {
                     if (readException !=  null ){
                         readException.addSuppressed(ex2);     // Note that there
                     } else {
                         readException = ex2;
                     }
                 }
             }
             if (readException !=  null ){
                 throw  readException;
             }
         }
     }
}

The key to this is to put finally The exception generated in the statement is passed through addSuppressed The method is added to try In the exception generated by the statement .

One catch Clause catches multiple exceptions

stay Java7 In the previous exception handling Syntax , One catch Clause can only catch one type of exception . This restriction can be cumbersome when there are many kinds of exceptions to handle . Each exception needs to add a catch Clause , And these catch The processing logic in the clause may all be the same , This can cause code duplication . Although you can catch Clause to capture all exceptions through the base class of these exceptions often , For example, use Exception As the type of capture , But this requires the same handling of these different exceptions . In addition, it is possible to catch some non checked exceptions that should not be caught . And in the In some cases , Code duplication is inevitable . For example, a method might throw 4 It's a different anomaly , Among them is 2 Two exceptions are handled in the same way , in addition 2 The two exceptions are handled in the same way , But it's different from Ahead 2 Species abnormality . This is bound to happen in catch Clause contains duplicate code .

In this case ,Java7 Improved catch Syntax of clause , Multiple exceptions are allowed to be specified , Use... Between each exception type “|” To separate . For example :

?
1
2
3
4
5
6
7
8
9
10
11
package  test;
 
public  class  ExceptionHandler {
     public  void  handle(){
         try  {
             //..............
         catch  (ExceptionA | ExceptionB ab) { 
         catch  (ExceptionC c) {    
         }
     }
}

This new way of dealing with the problems mentioned above has been well solved . It should be noted that , stay catch Statement in clause , You can't have duplicate types , One exception is not allowed to be a subclass of another exception , Otherwise, there will be compilation errors . If in catch More than one exception class is declared in clause , Then the specific type of exception parameter is the minimum upper bound of all these exception types .

About a catch An exception type in a clause cannot be a subclass of another , It actually involves the internal implementation of catching multiple exceptions . such as :

?
1
2
3
4
5
public  void  testSequence() {
     try  {
         Integer.parseInt( "Hello" );
     catch  (NumberFormatException | RuntimeException e){}
}

Like this code up here , although NumberFormatException yes RuntimeException Subclasses of , But this code can be compiled . however , If you put catch The declaration position of two exceptions in clause is changed , There will be compilation errors . For example :

?
1
2
3
4
5
public  void  testSequenceError() {
     try  {
         Integer.parseInt( "Hello" );
     catch  (RuntimeException | NumberFormatException e) {}
}

The reason lies in , The compiler's approach is to capture multiple exceptions catch Clause into multiple catch Clause , At every catch Clause . The above code is equivalent to :

?
1
2
3
4
5
6
7
public  void  testSequenceError() {
     try  {
         Integer.parseInt( "Hello" );
     catch  (RuntimeException e) {
     catch  (NumberFormatException e) {
     }
}

come from :http://my.oschina.net/fhd/blog/324484

Java7 New features of exception handling for -addSuppressed() Methods and so on

  1. Happy bytes -Java8 New feature method references

    In the last article, Xiaole introduced <Java8 New characteristics - Functional interface >, You can click review . This article will go on to introduce Java8 New feature method references . Java8 Introduce methods to reference new features , Used to simplify the call of application object methods ,  Method reference ...

  2. java7 and java8 New characteristics

    Go down to the website : http://blog.csdn.net/samjustin1/article/details/52268004 Java7 New characteristics 1.switch String can be used in String ...

  3. Java 8 New characteristics -4 Method reference

    For references, we usually use them in objects , The characteristic of object reference is : Different reference objects can manipulate the same piece of content ! Java 8 The method reference of defines four formats : Reference static methods     ClassName :: staticMetho ...

  4. java8 New characteristics - The default method

    As a java Program the ape , I'm often asked how the foundation is , For this question , I understand it in two ways : One is about java Basic understanding and mastery , such as JDK Related characteristics of : Second, work experience , After all , Language programming is a practical art , Even if you master ten million ...

  5. jdk1.8 New feature method references

    A method reference is actually a method call , The symbol is two colons :: To express , On the left are objects or classes , On the right is the method . It's really just lambda Further simplification of the expression . If not used lambda expression , Then there is no need to use method reference . What is lambda, ginseng ...

  6. Java7 The new features of

    This paper introduces java 7 New features, a lot of other things like grammar candy . After all java It's in good condition . There are a lot of imperfections, which are difficult to implement or depend on some underlying ( Like the operating system ) The function of . however java7 It's similar to aio The power of . ...

  7. Java8 New characteristics The default method

    Why does the default method appear The default method appears because of java8 In the process of design , Because of joining Lamdba expression , And functional interfaces , So we need to add new methods to a lot of interfaces , But if you add new methods directly to the interface , So all the things I wrote before ...

  8. 2020 You don't know yet Java8 New characteristics ? Method citation and Stream Flow introduction and detailed explanation of operation mode ( 3、 ... and )

    Method reference details Method reference : method reference Method references are actually Lambda A grammatical sugar of expressions We can think of a method reference as a 「 A function pointer 」,function pointer Method references are divided into 4 ...

  9. Java 5/Java 6/Java7/Java 8 New feature collection

    Preface : Java 8 Corresponding JDK Version is JDK8, And when you download it from the official website and install it , The folder says JDK1.8, The same meaning .( And the naming of this version is also regular , And so on ) One .Java 5 1.https://seg ...

Random recommendation

  1. 【HDU 1542】Atlantis( Line segment tree + discretization , Rectangular area and )

    Find the area of a rectangle and , Discrete plus line tree . Scanning line method : Use parallel x The linear sweep of the axis , Every time ans+=( Next height - Current altitude )* The width of the current overlay . #include<algorithm> #include<c ...

  2. C++ Read pcap file .

    http://blog.csdn.net/haolipengzhanshen/article/details/51854853 1. Get to know pcap File structure 2. Definition pcap File header structure pcapFi ...

  3. delphi call java Of WebService Server side .

    // InvRegistry.RegisterInvokeOptions(TypeInfo(ModelADServicePortType), ioLiteral); InvRegistry.Regis ...

  4. Jmeter perform java Prompt at the end of the script :he JVM should have exitted but did not

    Use jmeter perform java At the end of the protocol test :he JVM should have exitted but did not ,jmeter2.11 The future can be By setting :      jmeteren ...

  5. MSSQL - Stored procedure things

    effect : Create stored procedures with things : use sales -- Specify database create table bb -- establish bb This table ( ID int not null primary key ,-- account number Mo ...

  6. Android Studio Use ( 5、 ... and )-- Import third party Jar package

    This blog post will introduce how to import the third party Jar package . 1. First of all, I will download Jar Bag direct Copy To libs Below directory , Then right-click Jar file , Click on Add As Library after , Click OK in the pop-up box . 2. open bui ...

  7. Appium python Automatic test series page sliding principle explanation ( Ten )

    10.1.1 Page sliding principle analysis In the section of page sliding search, we talked about the knowledge of sliding , I just don't know if you have practiced and understood , If you practice hard . I understand. Then I believe this chapter can be completed without looking at it , Now let's make a brief analysis ...

  8. maven Introduction in oracle The driver reports an error Missing artifact com.oracle:ojdbc14:jar:10.2.0.4.0

    from https://blog.csdn.net/lovesomnus/article/details/49512777 stay maven Find... In the central library ojdbc, The latest version found is 10.2.0.4.0, And then in ...

  9. solve PuTTY Chinese garbled

    Reprint :http://lhdeyx.blog.163.com/blog/static/3181969720091115113716947/ open putty, choice  Category Medium Windows--- ...

  10. RedHat 7 install PostgreSQL 10.5

    System environment Redhat: Version: 7.4.1708 Architecture: x86_64 Address: 10.127.1.11 User: root Uassword: redhat ...