chapter04_Java基础知识_12_异常处理

本文深入探讨Java中finally块的执行机制,包括其对return语句的影响,以及在处理基本类型与引用类型时的不同表现。同时,文章还详细解释了Java异常处理机制,包括Error与Exception的区别,检查异常与运行时异常的分类,以及异常如何在多线程环境中被处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • finally

    (1) finally块中的语句一般总会被执行,如果try中包含了return方法,那么可以理解为finally块中的部分类似于内联函数,插入到return前面执行,然后再执行return

    (2) (1)造成的结果是,如果finally块中包含了return语句,会覆盖其他地方的return

    示例

      class Test {
    
          private static int testBasicType() {
    
              int result = 1;
      
              try {
                  result = 2;
                  return result;
              } catch (Exception e) {
                  return 0;
              } finally {
                  result = 3;
                  return result;
              }
          }
    
          public static void main(String[] args) {
    
              System.out.println(testBasicType());
          }
      }
    

    输出3

    (3) 如果finally块中不包含return语句,当返回基本类型时,finally块中对return的变量的赋值不影响返回结果

      class Test {
    
          private static int testBasicType() {
    
              int result = 1;
              
              try {
                  result = 2;
                  return result;
              } catch (Exception e) {
                  return 0;
              } finally {
                  result = 3;
              }
          }
    
          public static void main(String[] args) {
    
              System.out.println(testBasicType());
          }
      }
    

    输出2.原因是在return之后,栈帧会回收所有数据,因此return前要把基本类型的值保存好,此时执行finally方法,无论是否改变变量的值,return的都是保存好的值,因此不会影响返回结果

    (4) 如果finally块中不包含return语句,当返回引用类型时,finally块中对return的变量的赋值会影响返回结果

    示例

      class Test {
    
          private static int[] testReferenceType() {
    
              int[] result = {1,2};
    
              try {
                  return result;
              } catch (Exception e) {
                  return null;
              } finally {
                  result[1] = 3;
              }
          }
    
          public static void main(String[] args) {
    
              System.out.println(Arrays.toString(testReferenceType()));
          }
      }
    

    输出[1, 3]。原因是return前会保存好result在堆中的地址,由于finally块中的语句改变的是堆中的值,因此尽管返回的地址没变,但是堆中的内容已经被改变

    (5) 不会执行finally块的情况

    1° 在try之前就发生错误

    2° try中强制退出:System.exit(0);

  • 异常的分类

    (1) Error类和Exception类都从Throwable类派生。 Error表示程序运行期间出现了严重的错误,不可恢复;Exception表示可恢复的异常

    (2) Exception分为__检查异常__ 和 运行时异常

    检查异常:编译时由编译器强制程序捕捉异常,如IOException, SQLException

    运行时异常:运行时出现的异常,如NullPointerException, ArrayIndexOutOfBoundsException

  • (1) 出现运行时异常后,会把异常一直向上层抛出,直到遇到可以catch该异常的代码

    (2) 如果一直没有异常处理,对于__单线程程序__,会从main()抛出,程序终止;对于__多线程程序__,从Thread.run()抛出,线程终止

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值