74_异常机制_try_catch_finally_return执行顺序

来源:互联网 发布:医疗软件注册证 编辑:程序博客网 时间:2024/06/07 14:21

异常的处理办法之一,捕获异常

这里写图片描述
上面过程详细解析:

try块

try语句指定了一段代码,该段代码就是一次捕获并处理的范围。在执行过程中,当任意一条语句产生异常时,就会跳过该段中后面的代码。代码中可能会产生并抛出一种或几种类型的异常对象,它后面的catch语句要分别对这些异常做相应的处理
一个try语句必须带有至少一个catch语句块或一个finally语句块 。。
注:当异常处理的代码执行结束以后,是不会回到try语句去执行尚未执行的代码。

catch

  • 每个try语句块可以伴随一个或多个catch语句,用于处理可能产生的不同类型的异常对象。
  • 常用方法:

    • toString ( )方法,显示异常的类名和产生异常的原因
    • getMessage( ) 方法,只显示产生异常的原因,但不显示类名。
    • printStackTrace( ) 方法,用来跟踪异常事件发生时堆栈的内容。

    这些方法均继承自Throwable类

  • Catch捕获异常时的捕获顺序:
    如果异常类之间有继承关系,在顺序安排上需注意。越是顶层的类,越放在下面。再不然就直接把多余的catch省略掉。

finally

  • 有些语句,不管是否发生了异常,都必须要执行,那么就可以把这样的语句放到finally语句块中。
  • 通常在finally中关闭程序块已打开的资源,比如:文件流、释放数据库连接等。

代码

import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;public class TestException {    public static void main(String[] args) {        FileReader reader = null;        try {            reader = new FileReader("d:/a.txt");            char temp = (char) reader.read();            System.out.println("读出的内容:" + temp);        } catch (FileNotFoundException e) {            System.out.println("文件没有找到!!");            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();            System.out.println("文件读取错误!");        } finally {            System.out.println(" 不管有没有异常,我肯定会被执行!");            try {                reader.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }}

try, catch,finally ,return 执行顺序

  • 执行顺序:
    1. 执行try,catch , 给返回值赋值
    2. 执行finally
    3. return
import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;public class TestException {    public static void main(String[] args) {        String str = new TestException().openFile();        System.out.println(str);    }    String openFile() {        try {            System.out.println("aaa");            FileInputStream fis = new FileInputStream("d:/a.txt");            int a = fis.read();            System.out.println("bbb");            return "step1";        } catch (FileNotFoundException e) {            System.out.println("catching !!!!!");            e.printStackTrace();            return "step2";// 先确定返回值,并不会直接结束运行。        } catch (IOException e) {            e.printStackTrace();            return "step3";        } finally {            System.out.println("finally !!!!!");            // return "fff";不要在finally中使用return.        }    }}