zoukankan      html  css  js  c++  java
  • try/catch中finally的执行时间

    前言 由于总是搞不清楚try/catch中的一个执行顺序,返回结果。所以总结一下 1.finally没有return 时,可以看出finally确实在return之前执行了 public static void main(String[] args) { int aa = test1(); System.out.println(aa); } public static int test1(){ try{ System.out.println("try"); return 0; }catch(Exception e){ System.out.println("catch"); return 1; }finally { System.out.println("finally"); } } //结果 //try //finally //0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 2. finally有return 时,会覆盖其他语句中的return public static void main(String[] args) { int aa = test1(); System.out.println(aa); } public static int test1(){ try{ System.out.println("try"); return 0; }catch(Exception e){ System.out.println("catch"); return 1; }finally { System.out.println("finally"); return 2; } } //结果 //try //finally //2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 3.finally中对基本数据类型没有影响 public static int test1(){ int result = 6; try{ System.out.println("try"); return result; }catch(Exception e){ System.out.println("catch"); return 1; }finally { System.out.println("finally"); result = 3; } } //结果try //finally //6 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 4.finally中对引用型数据有影响 public static StringBuffer test1(){ StringBuffer str = new StringBuffer("I"); try{ System.out.println("try"); return str; }catch(Exception e){ System.out.println("catch"); return null; }finally { System.out.println("finally"); str.append("am"); } } //结果try //finally // I am 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 5.当try/catch外面有异常,finally不执行 public static int test2(){ int a = 5/0; try{ System.out.println("try"); return a; }catch(Exception e){ System.out.println("catch"); return 2; }finally { System.out.println("finally"); } } 1 2 3 4 5 6 7 8 9 10 11 12 Exception in thread "main" java.lang.ArithmeticException: / by zero at com.jxl.face.Controller.EnumTest.test2(EnumTest.java:29) at com.jxl.face.Controller.EnumTest.main(EnumTest.java:19) 1 2 3 4 6.异常在try/catch里面,finally无return public static int test2(){ try{ int a = 5/0; System.out.println("try"); return a; }catch(Exception e){ System.out.println("catch"); return 2; }finally { System.out.println("finally"); } } //catch //finally //2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 7.异常在try/catch里面,finally有return public static int test2(){ try{ int a = 5/0; System.out.println("try"); return a; }catch(Exception e){ System.out.println("catch"); return 2; }finally { System.out.println("finally"); return 3; } } //catch //finally //3
  • 相关阅读:
    Object-C中
    实例变量可见度修饰符
    Object-C 类和对象
    C语言中线程和进程的区别
    动态内存分配
    C语言中union关键字
    C语言结构体
    const define static extern 关键词详解
    基于TensorFlow Object Detection API进行迁移学习训练自己的人脸检测模型(一)
    Ubuntu18.04+CUDA9.0+cuDNN7.1.3+TensorFlow1.8 安装总结
  • 原文地址:https://www.cnblogs.com/exmyth/p/10744184.html
Copyright © 2011-2022 走看看