java抛出异常与finally实例解析
这篇文章主要介绍了java抛出异常与finally实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
代码如下:
package test1; public class EmbededFinally { public static void main(String args[]) { int result; try { System.out.println("in Level 1"); try { System.out.println("in Level 2"); // result=100/0; //Level 2 try { System.out.println("in Level 3"); result=100/0; //Level 3 } catch (Exception e) { System.out.println("Level 3:" + e.getClass().toString()); } finally { System.out.println("In Level 3 finally"); } // result=100/0; //Level 2 } catch (Exception e) { System.out.println("Level 2:" + e.getClass().toString()); } finally { System.out.println("In Level 2 finally"); } // result = 100 / 0; //level 1 } catch (Exception e) { System.out.println("Level 1:" + e.getClass().toString()); } finally { System.out.println("In Level 1 finally"); } } }
运行结果如上图:
对于代码的分析: 前三行输出结果,是try中三个正常的输出语句,并且在最后抛出了一个by zero错误。然后用catch语句捕捉了这个语句,并且输出了语句。但我们会发现后面的catch语句都没有被执行,而是直接执行了finally语句,说明finally语句改变了代码中输出的逻辑。但具体的原因尚不明确。
最后,提出一个小问题:finally语句一定会执行吗?
我姑且自己回答一下,如果在finally之前使用了exit,退出了程序,那么finally语句就不会执行了。
比如,我们用以下的测试代码:
package test1; public class SystemExitAndFinally { public static void main(String[] args) { try{ System.out.println("in main"); throw new Exception("Exception is thrown in main"); //System.exit(0); } catch(Exception e) { System.out.println(e.getMessage()); System.exit(0); } finally { System.out.println("in finally"); } } }
运行结果如图:
我们可以看到,finally后的语句并没有被输出,而在退出程序前的语句并没有任何影响。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
SpringMVC使用@PathVariable接收参数过程解析
这篇文章主要介绍了SpringMVC使用@PathVariable接收参数过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下2020-10-10Java使用Apache compress实现文件夹压缩成Zip包
Apache common提供了很多实用的工具包,这篇文章主要来和大家介绍一下Java如何使用Apache compress包实现文件夹压缩成Zip包,希望对大家有所帮助2024-01-01SpringCloud超详细讲解负载均衡组件Ribbon源码
在微服务中,对服务进行拆分之后,必然会带来微服务之间的通信需求,而每个微服务为了保证高可用性,又会去部署集群,那么面对一个集群微服务进行通信的时候,如何进行负载均衡也是必然需要考虑的问题2022-07-07
最新评论