【Java学习笔记之三十三】详解Java中try,catch,finally的用法及分析

简介: 这一篇我们将会介绍java中try,catch,finally的用法 以下先给出try,catch用法: try {   //需要被检测的异常代码 } catch(Exception e) { //异常处理,即处理异常代码 } finally {   //一定会被执行的代码 } 代码区如果有错误,就会返回所写异常的处理。

这一篇我们将会介绍java中try,catch,finally的用法

以下先给出try,catch用法:

try
{

  //需要被检测的异常代码

}
catch(Exception e)
{
    //异常处理,即处理异常代码
}
finally
{

  //一定会被执行的代码

}

代码区如果有错误,就会返回所写异常的处理。

首先要清楚,如果没有try的话,出现异常会导致程序崩溃。而try则可以保证程序的正常运行下去,比如说:

try
{
    int i = 1/0;
}
catch(Exception e)
{
    ........
}

一个计算的话,如果除数为0,则会报错,如果没有try的话,程序直接崩溃。用try的话,则可以让程序运行下去,并且输出为什么出错!

try catch 是捕捉try部分的异常,当你没有trycatch的时候,如果出现异常则程序报错,加上try,catch,出现异常程序正常运行,只是把错误信息存储到Exception里,所以catch是用来提取异常信息的,你可以在catch部分加上一句System.out.println(e.ToString());,如果出现异常可以把异常打印出来~~

 

java的异常处理机制(try…catch…finally)

1 引子

try…catch…finally恐怕是大家再熟悉不过的语句了,而且感觉用起来也是很简单,逻辑上似乎也是很容易理解。不过,我亲自体验的“教训”告诉我,这个东西可不是想象中的那么简单、听话。不信?那你看看下面的代码,“猜猜”它执行后的结果会是什么?不要往后看答案、也不许执行代码看真正答案哦。如果你的答案是正确,那么这篇文章你就不用浪费时间看啦。

 1 public class TestException
 2 {
 3     public TestException()
 4     {
 5     }
 6     boolean testEx() throws Exception
 7     {
 8         boolean ret = true;
 9         try
10         {
11             ret = testEx1();
12         }
13         catch (Exception e)
14         {
15             System.out.println("testEx, catch exception");
16             ret = false;
17             throw e;
18         }
19         finally
20         {
21             System.out.println("testEx, finally; return value=" + ret);
22             return ret;
23         }
24     }
25     boolean testEx1() throws Exception
26     {
27         boolean ret = true;
28         try
29         {
30             ret = testEx2();
31             if (!ret)
32             {
33                 return false;
34             }
35             System.out.println("testEx1, at the end of try");
36             return ret;
37         }
38         catch (Exception e)
39         {
40             System.out.println("testEx1, catch exception");
41             ret = false;
42             throw e;
43         }
44         finally
45         {
46             System.out.println("testEx1, finally; return value=" + ret);
47             return ret;
48         }
49     }
50     boolean testEx2() throws Exception
51     {
52         boolean ret = true;
53         try
54         {
55             int b = 12;
56             int c;
57             for (int i = 2; i >= -2; i--)
58             {
59                 c = b / i;
60                 System.out.println("i=" + i);
61             }
62             return true;
63         }
64         catch (Exception e)
65         {
66             System.out.println("testEx2, catch exception");
67             ret = false;
68             throw e;
69         }
70         finally
71         {
72             System.out.println("testEx2, finally; return value=" + ret);
73             return ret;
74         }
75     }
76     public static void main(String[] args)
77     {
78         TestException testException1 = new TestException();
79         try
80         {
81             testException1.testEx();
82         }
83         catch (Exception e)
84         {
85             e.printStackTrace();
86         }
87     }
88 }

你的答案是什么?是下面的答案吗?

i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, catch exception
testEx1, finally; return value=false
testEx, catch exception
testEx, finally; return value=false

如果你的答案真的如上面所说,那么你错啦。^_^,那就建议你仔细看一看这篇文章或者拿上面的代码按各种不同的情况修改、执行、测试,你会发现有很多事情不是原来想象中的那么简单的。
现在公布正确答案:

i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, finally; return value=false
testEx, finally; return value=false

2 基础知识

2.1 相关概念

例外是在程序运行过程中发生的异常事件,比如除0溢出、数组越界、文件找不到等,这些事件的发生将阻止程序的正常运行。为了加强程序的鲁棒性,程序设计时,必须考虑到可能发生的异常事件并做出相应的处理。C语言中,通过使用if语句来判断是否出现了例外,同时,调用函数通过被调用函数的返回值感知在被调用函数中产生的例外事件并进行处理。全程变量ErroNo常常用来反映一个异常事件的类型。但是,这种错误处理机制会导致不少问题。
Java通过面向对象的方法来处理例外。在一个方法的运行过程中,如果发生了例外,则这个方法生成代表该例外的一个对象,并把它交给运行时系统,运行时系统寻找相应的代码来处理这一例外。我们把生成例外对象并把它提交给运行时系统的过程称为抛弃(throw)一个例外。运行时系统在方法的调用栈中查找,从生成例外的方法开始进行回朔,直到找到包含相应例外处理的方法为止,这一个过程称为捕获(catch)一个例外。

2.2 Throwable类及其子类  

用面向对象的方法处理例外,就必须建立类的层次。类 Throwable位于这一类层次的最顶层,只有它的后代才可以做为一个例外被抛弃。图1表示了例外处理的类层次。
从图中可以看出,类Throwable有两个直接子类:Error和Exception。Error类对象(如动态连接错误等),由Java虚拟机生成并抛弃(通常,Java程序不对这类例外进行处理);Exception类对象是Java程序处理或抛弃的对象。它有各种不同的子类分别对应于不同类型的例外。其中类RuntimeException代表运行时由Java虚拟机生成的例外,如算术运算例外ArithmeticException(由除0错等导致)、数组越界例外ArrayIndexOutOfBoundsException等;其它则为非运行时例外,如输入输出例外IOException等。Java编译器要求Java程序必须捕获或声明所有的非运行时例外,但对运行时例外可以不做处理。

2.3 异常处理关键字

Java的异常处理是通过5个关键字来实现的:try,catch,throw,throws,finally。JB的在线帮助中对这几个关键字是这样解释的:
Throws:  Lists the exceptions a method could throw.
Throw:   Transfers control of the method to the exception handler.
Try:    Opening exception-handling statement.
Catch:  Captures the exception.
Finally: Runs its code before terminating the program.

2.3.1 try语句 

try语句用大括号{}指定了一段代码,该段代码可能会抛弃一个或多个例外。

2.3.2 catch语句 

catch语句的参数类似于方法的声明,包括一个例外类型和一个例外对象。例外类型必须为Throwable类的子类,它指明了catch语句所处理的例外类型,例外对象则由运行时系统在try所指定的代码块中生成并被捕获,大括号中包含对象的处理,其中可以调用对象的方法。
catch语句可以有多个,分别处理不同类的例外。Java运行时系统从上到下分别对每个catch语句处理的例外类型进行检测,直到找到类型相匹配的catch语句为止。这里,类型匹配指catch所处理的例外类型与生成的例外对象的类型完全一致或者是它的父类,因此,catch语句的排列顺序应该是从特殊到一般。
也可以用一个catch语句处理多个例外类型,这时它的例外类型参数应该是这多个例外类型的父类,程序设计中要根据具体的情况来选择catch语句的例外处理类型。 

2.3.3 finally语句

try所限定的代码中,当抛弃一个例外时,其后的代码不会被执行。通过finally语句可以指定一块代码。无论try所指定的程序块中抛弃或不抛弃例外,也无论catch语句的例外类型是否与所抛弃的例外的类型一致,finally所指定的代码都要被执行,它提供了统一的出口。通常在finally语句中可以进行资源的清除工作。如关闭打开的文件等。

2.3.4 throws语句 

throws总是出现在一个函数头中,用来标明该成员函数可能抛出的各种异常。对大多数Exception子类来说,Java 编译器会强迫你声明在一个成员函数中抛出的异常的类型。如果异常的类型是Error或 RuntimeException, 或它们的子类,这个规则不起作用, 因为这在程序的正常部分中是不期待出现的。 如果你想明确地抛出一个RuntimeException,你必须用throws语句来声明它的类型。

2.3.5 throw语句 

throw总是出现在函数体中,用来抛出一个异常。程序会在throw语句后立即终止,它后面的语句执行不到,然后在包含它的所有try块中(可能在上层调用函数中)从里向外寻找含有与其匹配的catch子句的try块。

3 关键字及其中语句流程详解

3.1 try的嵌套

你可以在一个成员函数调用的外面写一个try语句,在这个成员函数内部,写另一个try语句保护其他代码。每当遇到一个try语句,异常的框架就放到堆栈上面,直到所有的try语句都完成。如果下一级的try语句没有对某种异常进行处理,堆栈就会展开,直到遇到有处理这种异常的try语句。下面是一个try语句嵌套的例子。

 1 class MultiNest {
 2     static void procedure() {
 3         try {
 4             int a = 0;
 5             int b = 42/a;
 6         } catch(java.lang.ArithmeticException e) {
 7             System.out.println("in procedure, catch ArithmeticException: " + e);
 8         }
 9     }
10     public static void main(String args[]) {
11         try {
12             procedure();
13         } catch(java.lang. Exception e) {
14             System.out.println("in main, catch Exception: " + e);
15         }
16     }
17 }

这个例子执行的结果为:

in procedure, catch ArithmeticException: java.lang.ArithmeticException: / by zero

 

成员函数procedure里有自己的try/catch控制,所以main不用去处理 ArrayIndexOutOfBoundsExc

eption;当然如果如同最开始我们做测试的例子一样,在procedure中catch到异常时使用throw e;语句将异常抛出,那么main当然还是能够捕捉并处理这个procedure抛出来的异常。例如在procedure函数的catch中的System.out语句后面增加throw e;语句之后,执行结果就变为:

in procedure, catch ArithmeticException: java.lang.ArithmeticException: / by zero
in main, catch Exception: java.lang.ArithmeticException: / by zero

3.2 try-catch程序块的执行流程以及执行结果

相对于try-catch-finally程序块而言,try-catch的执行流程以及执行结果还是比较简单的。
首先执行的是try语句块中的语句,这时可能会有以下三种情况:
    1.如果try块中所有语句正常执行完毕,那么就不会有其他的“动做”被执行,整个try-catch程序块正常完成。
    2.如果try语句块在执行过程中碰到异常V,这时又分为两种情况进行处理:
-->如果异常V能够被与try相应的catch块catch到,那么第一个catch到这个异常的catch块(也是离try最近的一个与异常V匹配的catch块)将被执行;如果catch块执行正常,那么try-catch程序块的结果就是“正常完成”;如果该catch块由于原因R突然中止,那么try-catch程序块的结果就是“由于原因R突然中止(completes abruptly)”。
-->如果异常V没有catch块与之匹配,那么这个try-catch程序块的结果就是“由于抛出异常V而突然中止(completes abruptly)”。
    3. 如果try由于其他原因R突然中止(completes abruptly),那么这个try-catch程序块的结果就是“由于原因R突然中止(completes abruptly)”。

3.3 try-catch-finally程序块的执行流程以及执行结果

try-catch-finally程序块的执行流程以及执行结果比较复杂。
首先执行的是try语句块中的语句,这时可能会有以下三种情况:
1.如果try块中所有语句正常执行完毕,那么finally块的居于就会被执行,这时分为以下两种情况:
-->如果finally块执行顺利,那么整个try-catch-finally程序块正常完成。
-->如果finally块由于原因R突然中止,那么try-catch-finally程序块的结局是“由于原因R突然中止(completes abruptly)”
2.如果try语句块在执行过程中碰到异常V,这时又分为两种情况进行处理:
-->如果异常V能够被与try相应的catch块catch到,那么第一个catch到这个异常的catch块(也是离try最近的一个与异常V匹配的catch块)将被执行;这时就会有两种执行结果:
-->如果catch块执行正常,那么finally块将会被执行,这时分为两种情况:
-->如果finally块执行顺利,那么整个try-catch-finally程序块正常完成。
-->如果finally块由于原因R突然中止,那么try-catch-finally程序块的结局是“由于原因R突然中止(completes abruptly)”
-->如果catch块由于原因R突然中止,那么finally模块将被执行,分为两种情况:
-->如果如果finally块执行顺利,那么整个try-catch-finally程序块的结局是“由于原因R突然中止(completes abruptly)”。
-->如果finally块由于原因S突然中止,那么整个try-catch-finally程序块的结局是“由于原因S突然中止(completes abruptly)”,原因R将被抛弃。
(注意,这里就正好和我们的例子相符合,虽然我们在testEx2中使用throw e抛出了异常,但是由于testEx2中有finally块,而finally块的执行结果是complete abruptly的(别小看这个用得最多的return,它也是一种导致complete abruptly的原因之一啊——后文中有关于导致complete abruptly的原因分析),所以整个try-catch-finally程序块的结果是“complete abruptly”,所以在testEx1中调用testEx2时是捕捉不到testEx1中抛出的那个异常的,而只能将finally中的return结果获取到。
如果在你的代码中期望通过捕捉被调用的下级函数的异常来给定返回值,那么一定要注意你所调用的下级函数中的finally语句,它有可能会使你throw出来的异常并不能真正被上级调用函数可见的。当然这种情况是可以避免的,以testEx2为例:如果你一定要使用finally而且又要将catch中throw的e在testEx1中被捕获到,那么你去掉testEx2中的finally中的return就可以了。
这个事情已经在OMC2.0的MIB中出现过啦:服务器的异常不能完全被反馈到客户端。)
-->如果异常V没有catch块与之匹配,那么finally模块将被执行,分为两种情况:
-->如果finally块执行顺利,那么整个try-catch-finally程序块的结局就是“由于抛出异常V而突然中止(completes abruptly)”。
-->如果finally块由于原因S突然中止,那么整个try-catch-finally程序块的结局是“由于原因S突然中止(completes abruptly)”,异常V将被抛弃。
3.如果try由于其他原因R突然中止(completes abruptly),那么finally块被执行,分为两种情况:
-->如果finally块执行顺利,那么整个try-catch-finally程序块的结局是“由于原因R突然中止(completes abruptly)”。
-->如果finally块由于原因S突然中止,那么整个try-catch-finally程序块的结局是“由于原因S突然中止(completes abruptly)”,原因R将被抛弃。
3.4 try-catch-finally程序块中的return
从上面的try-catch-finally程序块的执行流程以及执行结果一节中可以看出无论try或catch中发生了什么情况,finally都是会被执行的,那么写在try或者catch中的return语句也就不会真正的从该函数中跳出了,它的作用在这种情况下就变成了将控制权(语句流程)转到finally块中;这种情况下一定要注意返回值的处理。
例如,在try或者catch中return false了,而在finally中又return true,那么这种情况下不要期待你的try或者catch中的return false的返回值false被上级调用函数获取到,上级调用函数能够获取到的只是finally中的返回值,因为try或者catch中的return语句只是转移控制权的作用。
3.5 如何抛出异常
如果你知道你写的某个函数有可能抛出异常,而你又不想在这个函数中对异常进行处理,只是想把它抛出去让调用这个函数的上级调用函数进行处理,那么有两种方式可供选择:
第一种方式:直接在函数头中throws SomeException,函数体中不需要try/catch。比如将最开始的例子中的testEx2改为下面的方式,那么testEx1就能捕捉到testEx2抛出的异常了。

 1 boolean testEx2() throws Exception{
 2         boolean ret = true;
 3         int b=12;
 4         int c;
 5         for (int i=2;i>=-2;i--){
 6             c=b/i;
 7             System.out.println("i="+i);
 8         }
 9         return true;   
10 }

第二种方式:使用try/catch,在catch中进行一定的处理之后(如果有必要的话)抛出某种异常。例如上面的testEx2改为下面的方式,testEx1也能捕获到它抛出的异常:

 1 boolean testEx2() throws Exception{
 2         boolean ret = true;
 3         try{
 4             int b=12;
 5             int c;
 6             for (int i=2;i>=-2;i--){
 7                 c=b/i;
 8                 System.out.println("i="+i);
 9             }
10             return true;
11         }catch (Exception e){
12             System.out.println("testEx2, catch exception");
13             Throw e;
14         }
15 }

第三种方法:使用try/catch/finally,在catch中进行一定的处理之后(如果有必要的话)抛出某种异常。例如上面的testEx2改为下面的方式,testEx1也能捕获到它抛出的异常:

 1 boolean testEx2() throws Exception{
 2         boolean ret = true;
 3         try{
 4             int b=12;
 5             int c;
 6             for (int i=2;i>=-2;i--){
 7                 c=b/i;
 8                 System.out.println("i="+i);
 9                 throw new Exception("aaa");
10             }
11             return true;
12         }catch (java.lang.ArithmeticException e){
13             System.out.println("testEx2, catch exception");
14             ret = false;
15             throw new Exception("aaa");
16         }finally{
17             System.out.println("testEx2, finally; return value="+ret);
18         }
19 }

4.关于abrupt completion

前面提到了complete abruptly(暂且理解为“突然中止”或者“异常结束”吧),它主要包含了两种大的情形:abrupt completion of expressions and statements,下面就分两种情况进行解释。

4.1 Normal and Abrupt Completion of Evaluation

每一个表达式(expression)都有一种使得其包含的计算得以一步步进行的正常模式,如果每一步计算都被执行且没有异常抛出,那么就称这个表达式“正常结束(complete normally)”;如果这个表达式的计算抛出了异常,就称为“异常结束(complete abruptly)”。异常结束通常有一个相关联的原因(associated reason),通常也就是抛出一个异常V。
与表达式、操作符相关的运行期异常有:
-->A class instance creation expression, array creation expression , or string concatenation operatior expression throws an OutOfMemoryError if there is insufficient memory available.
-->An array creation expression throws a NegativeArraySizeException if the value of any dimension expression is less than zero.
-->A field access throws a NullPointerException if the value of the object reference  expression is null.
-->A method invocation expression that invokes an instance method throws a NullPointerException if the target reference is null.
-->An array access throws a NullPointerException if the value of the array reference  expression is null.
-->An array access throws an ArrayIndexOutOfBoundsException if the value of the array index expression is negative or greater than or equal to the length of the array.
-->A cast throws a ClassCastException if a cast is found to be impermissible at run time.
-->An integer division or integer remainder operator throws an ArithmeticException if the value of the right-hand operand expression is zero. -->An assignment to an array component of reference type throws an ArrayStoreException when the value to be assigned is not compatible with the component type of the array.

4.2 Normal and Abrupt Completion of Statements

正常情况我们就不多说了,在这里主要是列出了abrupt completion的几种情况:
-->break, continue, and return 语句将导致控制权的转换,从而使得statements不能正常地、完整地执行。
-->某些表达式的计算也可能从java虚拟机抛出异常,这些表达式在上一小节中已经总结过了;一个显式的的throw语句也将导致异常的抛出。抛出异常也是导致控制权的转换的原因(或者说是阻止statement正常结束的原因)。
如果上述事件发生了,那么这些statement就有可能使得其正常情况下应该都执行的语句不能完全被执行到,那么这些statement也就是被称为是complete abruptly.
导致abrupt completion的几种原因:
-->A break with no label
-->A break with a given label
-->A continue with no label
-->A continue with a given label
-->A return with no value
-->A return with a given value A
-->throw with a given value, including exceptions thrown by the Java virtual machine

下面看一个例子(例1),来讲解java里面中try、catch、finally的处理流程

 1 public class TryCatchFinally {
 2  
 3     @SuppressWarnings("finally")
 4     public static final String test() {
 5         String t = "";
 6  
 7         try {
 8             t = "try";
 9             return t;
10         } catch (Exception e) {
11             // result = "catch";
12             t = "catch";
13             return t;
14         } finally {
15             t = "finally";
16         }
17     }
18  
19     public static void main(String[] args) {
20         System.out.print(TryCatchFinally.test());
21     }
22  
23 }

  首先程序执行try语句块,把变量t赋值为try,由于没有发现异常,接下来执行finally语句块,把变量t赋值为finally,然后return t,则t的值是finally,最后t的值就是finally,程序结果应该显示finally,但是实际结果为try。为什么会这样,我们不妨先看看这段代码编译出来的class对应的字节码,看虚拟机内部是如何执行的。

我们用javap -verbose TryCatchFinally 来显示目标文件(.class文件)字节码信息

系统运行环境:mac os lion系统 64bit

jdk信息:Java(TM) SE Runtime Environment (build 1.6.0_29-b11-402-11M3527) Java HotSpot(TM) 64-Bit Server VM (build 20.4-b02-402, mixed mode)

编译出来的字节码部分信息,我们只看test方法,其他的先忽略掉

 1 public static final java.lang.String test();
 2   Code:
 3    Stack=1, Locals=4, Args_size=0
 4    0:    ldc    #16; //String 
 5    2:    astore_0
 6    3:    ldc    #18; //String try
 7    5:    astore_0
 8    6:    aload_0
 9    7:    astore_3
10    8:    ldc    #20; //String finally
11    10:    astore_0
12    11:    aload_3
13    12:    areturn
14    13:    astore_1
15    14:    ldc    #22; //String catch
16    16:    astore_0
17    17:    aload_0
18    18:    astore_3
19    19:    ldc    #20; //String finally
20    21:    astore_0
21    22:    aload_3
22    23:    areturn
23    24:    astore_2
24    25:    ldc    #20; //String finally
25    27:    astore_0
26    28:    aload_2
27    29:    athrow
28   Exception table:
29    from   to  target type
30     8    13   Class java/lang/Exception
31     8    24   any
32    19    24   any
33   LineNumberTable: 
34    line 5: 0
35    line 8: 3
36    line 9: 6
37    line 15: 8
38    line 9: 11
39    line 10: 13
40    line 12: 14
41    line 13: 17
42    line 15: 19
43    line 13: 22
44    line 14: 24
45    line 15: 25
46    line 16: 28
47 
48   LocalVariableTable: 
49    Start  Length  Slot  Name   Signature
50      27      0    t       Ljava/lang/String;
51      10      1    e       Ljava/lang/Exception;
52 
53   StackMapTable: number_of_entries = 2
54    frame_type = 255 /* full_frame */
55      offset_delta = 13
56      locals = [ class java/lang/String ]
57      stack = [ class java/lang/Exception ]
58    frame_type = 74 /* same_locals_1_stack_item */
59      stack = [ class java/lang/Throwable ]

首先看LocalVariableTable信息,这里面定义了两个变量 一个是t String类型,一个是e Exception 类型

接下来看Code部分

第[0-2]行,给第0个变量赋值“”,也就是String t="";

第[3-6]行,也就是执行try语句块 赋值语句 ,也就是 t = "try";

第7行,重点是第7行,把第s对应的值"try"付给第三个变量,但是这里面第三个变量并没有定义,这个比较奇怪

第[8-10] 行,对第0个变量进行赋值操作,也就是t="finally"

第[11-12]行,把第三个变量对应的值返回

通过字节码,我们发现,在try语句的return块中,return 返回的引用变量(t 是引用类型)并不是try语句外定义的引用变量t,而是系统重新定义了一个局部引用t’,这个引用指向了引用t对应的值,也就是try ,即使在finally语句中把引用t指向了值finally,因为return的返回引用已经不是t ,所以引用t的对应的值和try语句中的返回值无关了。

 

下面在看一个例子:(例2)

 1 public class TryCatchFinally {
 2 
 3     @SuppressWarnings("finally")
 4     public static final String test() {
 5         String t = "";
 6 
 7         try {
 8             t = "try";
 9             return t;
10         } catch (Exception e) {
11             // result = "catch";
12             t = "catch";
13             return t;
14         } finally {
15             t = "finally";
16             return t;
17         }
18     }
19 
20     public static void main(String[] args) {
21         System.out.print(TryCatchFinally.test());
22     }
23 
24 }

这里稍微修改了 第一段代码,只是在finally语句块里面加入了 一个 return t 的表达式。

按照第一段代码的解释,先进行try{}语句,然后在return之前把当前的t的值try保存到一个变量t',然后执行finally语句块,修改了变量t的值,在返回变量t。

这里面有两个return语句,但是程序到底返回的是try 还是 finally。接下来我们还是看字节码信息

 1 public static final java.lang.String test();
 2   Code:
 3    Stack=1, Locals=2, Args_size=0
 4    0:    ldc    #16; //String 
 5    2:    astore_0
 6    3:    ldc    #18; //String try
 7    5:    astore_0
 8    6:    goto    17
 9    9:    astore_1
10    10:    ldc    #20; //String catch
11    12:    astore_0
12    13:    goto    17
13    16:    pop
14    17:    ldc    #22; //String finally
15    19:    astore_0
16    20:    aload_0
17    21:    areturn
18   Exception table:
19    from   to  target type
20     9     9   Class java/lang/Exception
21    16    16   any
22   LineNumberTable: 
23    line 5: 0
24    line 8: 3
25    line 9: 6
26    line 10: 9
27    line 12: 10
28    line 13: 13
29    line 14: 16
30    line 15: 17
31    line 16: 20
32 
33   LocalVariableTable: 
34    Start  Length  Slot  Name   Signature
35      19      0    t       Ljava/lang/String;
36      6      1    e       Ljava/lang/Exception;
37 
38   StackMapTable: number_of_entries = 3
39    frame_type = 255 /* full_frame */
40      offset_delta = 9
41      locals = [ class java/lang/String ]
42      stack = [ class java/lang/Exception ]
43    frame_type = 70 /* same_locals_1_stack_item */
44      stack = [ class java/lang/Throwable ]
45    frame_type = 0 /* same */

这段代码翻译出来的字节码和第一段代码完全不同,还是继续看code属性

第[0-2]行、[3-5]行第一段代码逻辑类似,就是初始化t,把try中的t进行赋值try

第6行,这里面跳转到第17行,[17-19]就是执行finally里面的赋值语句,把变量t赋值为finally,然后返回t对应的值

我们发现try语句中的return语句给忽略。可能jvm认为一个方法里面有两个return语句并没有太大的意义,所以try中的return语句给忽略了,直接起作用的是finally中的return语句,所以这次返回的是finally。

 

接下来在看看复杂一点的例子:(例3)

 1 public class TryCatchFinally {
 2 
 3     @SuppressWarnings("finally")
 4     public static final String test() {
 5         String t = "";
 6 
 7         try {
 8             t = "try";
 9             Integer.parseInt(null);
10             return t;
11         } catch (Exception e) {
12             t = "catch";
13             return t;
14         } finally {
15             t = "finally";
16             // System.out.println(t);
17             // return t;
18         }
19     }
20 
21     public static void main(String[] args) {
22         System.out.print(TryCatchFinally.test());
23     }
24 
25 }

这里面try语句里面会抛出 java.lang.NumberFormatException,所以程序会先执行catch语句中的逻辑,t赋值为catch,在执行return之前,会把返回值保存到一个临时变量里面t ',执行finally的逻辑,t赋值为finally,但是返回值和t',所以变量t的值和返回值已经没有关系了,返回的是catch

例4:

 1 public class TryCatchFinally {
 2 
 3     @SuppressWarnings("finally")
 4     public static final String test() {
 5         String t = "";
 6 
 7         try {
 8             t = "try";
 9             Integer.parseInt(null);
10             return t;
11         } catch (Exception e) {
12             t = "catch";
13             return t;
14         } finally {
15             t = "finally";
16             return t;
17         }
18     }
19 
20     public static void main(String[] args) {
21         System.out.print(TryCatchFinally.test());
22     }
23 
24 }

这个和例2有点类似,由于try语句里面抛出异常,程序转入catch语句块,catch语句在执行return语句之前执行finally,而finally语句有return,则直接执行finally的语句值,返回finally

例5:

 1 public class TryCatchFinally {
 2 
 3     @SuppressWarnings("finally")
 4     public static final String test() {
 5         String t = "";
 6 
 7         try {
 8             t = "try";
 9             Integer.parseInt(null);
10             return t;
11         } catch (Exception e) {
12             t = "catch";
13             Integer.parseInt(null);
14             return t;
15         } finally {
16             t = "finally";
17             //return t;
18         }
19     }
20 
21     public static void main(String[] args) {
22         System.out.print(TryCatchFinally.test());
23     }
24 
25 }

这个例子在catch语句块添加了Integer.parser(null)语句,强制抛出了一个异常。然后finally语句块里面没有return语句。继续分析一下,由于try语句抛出异常,程序进入catch语句块,catch语句块又抛出一个异常,说明catch语句要退出,则执行finally语句块,对t进行赋值。然后catch语句块里面抛出异常。结果是抛出java.lang.NumberFormatException异常

例子6:

 1 public class TryCatchFinally {
 2 
 3     @SuppressWarnings("finally")
 4     public static final String test() {
 5         String t = "";
 6 
 7         try {
 8             t = "try";
 9             Integer.parseInt(null);
10             return t;
11         } catch (Exception e) {
12             t = "catch";
13             Integer.parseInt(null);
14             return t;
15         } finally {
16             t = "finally";
17             return t;
18         }
19     }
20 
21     public static void main(String[] args) {
22         System.out.print(TryCatchFinally.test());
23     }
24 
25 }

这个例子和上面例子中唯一不同的是,这个例子里面finally 语句里面有return语句块。try catch中运行的逻辑和上面例子一样,当catch语句块里面抛出异常之后,进入finally语句快,然后返回t。则程序忽略catch语句块里面抛出的异常信息,直接返回t对应的值 也就是finally。方法不会抛出异常

例子7:

 1 public class TryCatchFinally {
 2 
 3     @SuppressWarnings("finally")
 4     public static final String test() {
 5         String t = "";
 6 
 7         try {
 8             t = "try";
 9             Integer.parseInt(null);
10             return t;
11         } catch (NullPointerException e) {
12             t = "catch";
13             return t;
14         } finally {
15             t = "finally";
16         }
17     }
18 
19     public static void main(String[] args) {
20         System.out.print(TryCatchFinally.test());
21     }
22 
23 }

这个例子里面catch语句里面catch的是NPE异常,而不是java.lang.NumberFormatException异常,所以不会进入catch语句块,直接进入finally语句块,finally对s赋值之后,由try语句抛出java.lang.NumberFormatException异常。

例子8:

 1 public class TryCatchFinally {
 2 
 3     @SuppressWarnings("finally")
 4     public static final String test() {
 5         String t = "";
 6 
 7         try {
 8             t = "try";
 9             Integer.parseInt(null);
10             return t;
11         } catch (NullPointerException e) {
12             t = "catch";
13             return t;
14         } finally {
15             t = "finally";
16             return t;
17         }
18     }
19 
20     public static void main(String[] args) {
21         System.out.print(TryCatchFinally.test());
22     }
23 
24 }

和上面的例子中try catch的逻辑相同,try语句执行完成执行finally语句,finally赋值s 并且返回s ,最后程序结果返回finally

例子9:

 1 public class TryCatchFinally {
 2 
 3     @SuppressWarnings("finally")
 4     public static final String test() {
 5         String t = "";
 6 
 7         try {
 8             t = "try";return t;
 9         } catch (Exception e) {
10             t = "catch";
11             return t;
12         } finally {
13             t = "finally";
14             String.valueOf(null);
15             return t;
16         }
17     }
18 
19     public static void main(String[] args) {
20         System.out.print(TryCatchFinally.test());
21     }
22 
23 }

这个例子中,对finally语句中添加了String.valueOf(null), 强制抛出NPE异常。首先程序执行try语句,在返回执行,执行finally语句块,finally语句抛出NPE异常,整个结果返回NPE异常。

对以上所有的例子进行总结

1 try、catch、finally语句中,在如果try语句有return语句,则返回的之后当前try中变量此时对应的值,此后对变量做任何的修改,都不影响try中return的返回值

2 如果finally块中有return 语句,则返回try或catch中的返回语句忽略。

3 如果finally块中抛出异常,则整个try、catch、finally块中抛出异常

所以使用try、catch、finally语句块中需要注意的是

1 尽量在try或者catch中使用return语句。通过finally块中达到对try或者catch返回值修改是不可行的。

2 finally块中避免使用return语句,因为finally块中如果使用return语句,会显示的消化掉try、catch块中的异常信息,屏蔽了错误的发生

3 finally块中避免再次抛出异常,否则整个包含try语句块的方法回抛出异常,并且会消化掉try、catch块中的异常

5 关于我们的编程的一点建议

弄清楚try-catch-finally的执行情况后我们才能正确使用它。
如果我们使用的是try-catch-finally语句块,而我们又需要保证有异常时能够抛出异常,那么在finally语句中就不要使用return语句了(finally语句块的最重要的作用应该是释放申请的资源),因为finally中的return语句会导致我们的throw e被抛弃,在这个try-catch-finally的外面将只能看到finally中的返回值(除非在finally中抛出异常)。(我们需要记住:不仅throw语句是abrupt completion 的原因,return、break、continue等这些看起来很正常的语句也是导致abrupt completion的原因。)

 

目录
相关文章
|
11天前
|
Java
Java中的抽象类:深入了解抽象类的概念和用法
Java中的抽象类是一种不能实例化的特殊类,常作为其他类的父类模板,定义子类行为和属性。抽象类包含抽象方法(无实现)和非抽象方法。定义抽象类用`abstract`关键字,子类继承并实现抽象方法。抽象类适用于定义通用模板、复用代码和强制子类实现特定方法。优点是提供抽象模板和代码复用,缺点是限制继承灵活性和增加类复杂性。与接口相比,抽象类可包含成员变量和单继承。使用时注意设计合理的抽象类结构,谨慎使用抽象方法,并遵循命名规范。抽象类是提高代码质量的重要工具。
25 1
|
29天前
|
前端开发 Java
java中的Queue队列的用法
java中的Queue队列的用法
19 1
|
30天前
|
XML Java 编译器
java aspectjrt AOP 用法
java aspectjrt AOP 用法
21 0
|
1月前
|
算法 Java
java面向对象和面向过程分析
java面向对象和面向过程分析
36 0
|
9天前
|
Java 调度
Java中常见锁的分类及概念分析
Java中常见锁的分类及概念分析
14 0
|
9天前
|
Java
Java中ReentrantLock中tryLock()方法加锁分析
Java中ReentrantLock中tryLock()方法加锁分析
10 0
|
25天前
|
人工智能 监控 算法
java智慧城管源码 AI视频智能分析 可直接上项目
Java智慧城管源码实现AI视频智能分析,适用于直接部署项目。系统运用互联网、大数据、云计算和AI提升城市管理水平,采用“一级监督、二级指挥、四级联动”模式。功能涵盖AI智能检测(如占道广告、垃圾处理等)、执法办案、视频分析、统计分析及队伍管理等多个模块,利用深度学习优化城市管理自动化和智能化,提供决策支持。
200 4
java智慧城管源码 AI视频智能分析 可直接上项目
|
9天前
|
Java
Java中关于ConditionObject的signal()方法的分析
Java中关于ConditionObject的signal()方法的分析
21 4
|
9天前
|
Java
Java中关于ConditionObject的分析
Java中关于ConditionObject的分析
17 3