Use try-with-resources and multi-catch of

1. First of all, we talk about development before an exception is processed, we will use the try-catch-finally to handle exceptions.

//使用try-catch-finally
public
static void main(String[] args) { File file = null; FileReader fr = null; try { file = new File("D://abc.txt"); fr = new FileReader(file); }catch(FileNotFoundException e){ e.printStackTrace(); }finally { try { fr.close(); } catch(IOException e) { e.printStackTrace (); } } }

Through the code on the chart we can see, this approach makes the code is too complicated, if a little less need to turn off resources better, if more than three shut down, the code will be more complicated.

2. In order to solve this problem and optimize the future jdk7 a new approach, here we are introduced one by one.

(1) using the try-with-resources to handle exceptions

public static void main(String[] args) {

        try(FileReader fr = new FileReader("D://abc.txt");
            BufferedReader br = new BufferedReader(fr);){
            //对文件的操作
        }
        catch(FileNotFoundException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }

The try-with-resources usage format is:

the try (there's a resource will automatically shut down, provided that these resources must implement the interface or AutoCloseable Closeable Interface) { 

    // there is your other code 
} the catch (catch the exception) {
     // print exception information 
}   

(2) When using the try-with-resources to handle exceptions, we found that there are two catch catch exceptions, when you need more time to catch the exception, the code will become tedious,

  So we use multi-catch to solve this problem and optimization.

public  static  void main (String [] args) { 

        the try (the FileReader fr = new new the FileReader ( "D: //abc.txt" ); 
            the BufferedReader br = new new the BufferedReader (fr);) {
             // here only to demonstrate 
            IF ( new new . the Random () the nextInt (10) == 0 ) {
                 the throw  new new a ClassNotFoundException (); 
            } 
        } 
        catch (IOException | a ClassNotFoundException E) {// Note that this catch can not exist inside the exception-based parent child relationship. If there are sub-parent relationship, the parent simply capture it. 
            e.printStackTrace (); 
        } 
    }

 

Guess you like

Origin www.cnblogs.com/li666/p/12528874.html