try ... catch中Throw异常后的执行顺序

在Try ... Catch代码中, Throw异常后,throw后面的代码不再执行,直接执行Catch处的代码,并且Finally处的代码也会执行。

如果没有Catch语句,或者有Catch,但不符合异常处理的条件,则直接跳转到调用此代码的位置;如果还是没有catch,则继续回调,直到被处理或者回到最初的位置。


正常处理流程:

public static void main(String[] args) { // TODO Auto-generated method stub InputStream is = null; BufferedReader br = null; try { is = new FileInputStream("/home/min/log.txt"); br = new BufferedReader(new InputStreamReader(is)); if (br != null) { String str = null; while( (str = br.readLine())!= null ) { System.out.println(str); } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("--- FileNotFoundException ---"); return; // 加上return,也还是会执行finally区域的处理 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("--- IOException ---"); } finally { if (is != null) { try { is.close(); System.out.println("--- finally is.close ---"); } catch(IOException e) { System.out.println("--- finally is.close Exception ---"); } } if (br != null) { try { br.close(); System.out.println("--- finally br.close ---"); } catch(IOException e) { System.out.println("--- finally bis.close Exception ---"); } } System.out.println("--- finally ---"); } }

输出:
05-06 11:45:25.246: DEBUG/--------------(306): c = 0.02999999999999936
dsdasd
sdddd
end
--- finally is.close ---
--- finally br.close ---
--- finally ---

 

异常处理,把文件名改为一个不存在的文件:

public static void main(String[] args) { // TODO Auto-generated method stub InputStream is = null; BufferedReader br = null; try { is = new FileInputStream("/home/min/lssog.txt"); br = new BufferedReader(new InputStreamReader(is)); if (br != null) { String str = null; while( (str = br.readLine())!= null ) { System.out.println(str); } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("--- FileNotFoundException ---"); return; // 加上return,也还是会执行finally区域的处理 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("--- IOException ---"); } finally { if (is != null) { try { is.close(); System.out.println("--- finally is.close ---"); } catch(IOException e) { System.out.println("--- finally is.close Exception ---"); } } if (br != null) { try { br.close(); System.out.println("--- finally br.close ---"); } catch(IOException e) { System.out.println("--- finally bis.close Exception ---"); } } System.out.println("--- finally ---"); } }

 

输出:

java.io.FileNotFoundException: /home/min/lssog.txt (No such file or directory)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:106)
    at java.io.FileInputStream.<init>(FileInputStream.java:66)
    at com.min.test.JavaTest.main(JavaTest.java:20)
--- FileNotFoundException ---
--- finally ---

 

PS:无论是在try还是在catch块中加上return,都会执行fianlly区域的处理。

你可能感兴趣的:(c,exception,String,File,null)