zoukankan      html  css  js  c++  java
  • Java中try-catch-finally结合return执行顺序

    对于异常捕获及返回执行顺序的实验和总结

    • try{code1;return1} catch{code2;return2} finally {code3}
     1  public static void main(String[] args) {
     2         int flag=testtrycatch();
     3         System.out.println("flag:"+flag);
     4     }
     5     static int testtrycatch(){
     6             try {
     7                 int value =1/1;
     8                 return  111111;
     9             }catch (Exception e) {
    10                 System.out.println("catch"+e);
    11                 return  222222;
    12             }finally {
    13                 System.out.println("finally");
    14             }
    15     }

    无异常的返回,程序执行顺序是code1—code3—return1;

    输出:flag=111111

    有异常的返回,程序执行顺序是code2—code3—return2;

    输出:flag=222222

    • try{code1;return1} catch{code2} finally {code3}returnx
     1     public static void main(String[] args) {
     2         int flag=testtrycatch();
     3         System.out.println(flag);
     4     }
     5     static int testtrycatch(){
     6             try {
     7                 int value =1/0;
     8                 return  111111;
     9             }catch (Exception e) {
    10                 System.out.println("catch"+e);
    11             }finally {
    12                 System.out.println("finally");
    13             }
    14         return  333333;
    15     }

    无异常的返回,程序执行顺序是code1—code3—return1;

    输出:flag=111111

    有异常的返回,程序执行顺序是code2—code3—returnx;

    输出:flag=333333

    • try{code1;return1} catch{code2} finally {code3,return3}
     1     public static void main(String[] args) {
     2         int flag=testtrycatch();
     3         System.out.println(flag);
     4     }
     5     static int testtrycatch(){
     6             try {
     7                 int value =1/1;
     8                 return  111111;
     9             }catch (Exception e) {
    10                 System.out.println("catch"+e);
    11             }finally {
    12                 System.out.println("finally");
    13                 return  666666;
    14             }
    15     }

    无异常的返回,程序执行顺序是code1—code3—return3;

    输出:flag=666666

    有异常的返回,程序执行顺序是code2—code3—return3;

    输出:flag=666666

  • 相关阅读:
    [转]Android应用开发提高系列(5)——Android动态加载(下)——加载已安装APK中的类和资源
    [转]Eclipse中配置Struts2并实现HelloWorld
    [转]android4.0.3 修改启动动画和开机声音
    版本管理 Git
    [转]Android动态加载jar/dex
    [转]JSP 9 大内置对象详解
    [转]TMX Map Format Tiled地图格式
    [转]C++按行读取文本文件
    [转]Java——Servlet的配置和测试
    [转]android条形码编解码
  • 原文地址:https://www.cnblogs.com/apollo-shen/p/8058227.html
Copyright © 2011-2022 走看看