return语句在try-catch-finally中的执行顺序

简介:
    return语句在try-catch-finally中的执行顺序,这个问题很早在Q群上听闻,今天结合网上资料以及自己的实践,大体明白了:
  • 在try范围执行时抛出异常后,try里面剩余的代码不再执行,直接跳到catch
    public  class returnDemo{ 
       public  static  void main(String[] args) 
      { 
        Finally e =  new Finally(); 
        System.out.println(e.tryThis()); 
      } 
       
       public  int tryThis() 
      { 
         try
          System.out.println( "1"); 
           throw  new Exception(); 
           return 1; 
        } catch(Exception ex){ 
          System.out.println( "2"); 
           return 2; 
        } finally
          System.out.println( "4"); 
           return 3; 
        } 
         //System.out.println("5");  
      } 
    }
 
          在编译时,以上已经发生错误了:
          returnDemo.java:13: 无法访问的语句
                 return 1;
                ^
                1 错误
          可见在throw 异常后,return 1就无法访问(执行)了!
          在这里 System.out.println("5");   给注释了,否则编译时也会提示“无法访问的语句”!道理相信大家明白!
  • finally的return优先级最高
    public  class Finally{ 
       public  static  void main(String[] args) 
      { 
        Finally e= new Finally(); 
        System.out.println(e.tryThis()); 
      } 
       
       public  int tryThis() 
      { 
         try
          System.out.println( "1"); 
           throw  new Exception(); 
         //return 1; 
        } catch(Exception ex){ 
          System.out.println( "2"); 
           return 2; 
        } finally
          System.out.println( "4"); 
           return 3; 
        } 
      } 
    }
             执行结果:
            1
            2
            4
            3
            说明catch的 return 2; 是无效的,因为 return 3; 首要地返回了结果。 如果让try执行return,结果也是表明try的return 1;是无效的!

本文转自 Icansoft 51CTO博客,原文链接: http://blog.51cto.com/android/53141
相关文章
|
11月前
每日一道面试题之try-catch-finally 中,如果 catch 中 return 了,finally 还会执行吗?
每日一道面试题之try-catch-finally 中,如果 catch 中 return 了,finally 还会执行吗?
144 0
|
4月前
|
编译器
try{...}catch(){...}finally{...}语句你真的理解吗?
try{...}catch(){...}finally{...}语句你真的理解吗?
32 0
try catch finally,try 里面有 return,finally 还执行吗?
try catch finally,try 里面有 return,finally 还执行吗?
50 0
|
4月前
|
存储 缓存 IDE
细琢磨,try catch finally 执行顺序与返回值
细琢磨,try catch finally 执行顺序与返回值
52 0
|
4月前
|
设计模式 消息中间件 前端开发
finally中的代码一定会执行吗?
finally中的代码一定会执行吗?
487 0
try...catch中,catch加了return,后面的代码是不会执行的
try...catch中,catch加了return,后面的代码是不会执行的
96 0
|
存储 IDE Java
try catch finally 执行顺序总结
try catch finally 执行顺序总结
114 0
try catch return语句情况分析
简要讲述一下try catch代码中return语句返回值情况分析
|
JavaScript 前端开发
Throw 语句
Throw 语句
54 0
throw 语句
throw 语句
48 0