在JAVA中进行异常处理练习时,我对各种事情感到困惑.基本上我不明白的是当遇到异常时程序的流程如何.我想了解程序的流程实际上是如何在以下场景中进行的,以及我对这些概念的理解是对还是错.
public void myFunction(){ try{ //Some code...... }catch(Exception e1){ //If this Exception is occured handle it here. }catch(Exception e2){ //if this exception has occured then throw new myException("whatever message required"); } finally{ //code that has to be executed } }
现在我的理解是:
1.如果没有异常发生,则代码运行平稳,最终执行finally块中的代码
2.如果发生异常e1,那么它会被捕获到第一个catch块中,它会在那里被适当地处理,然后最终块被执行.
但是如果发生异常e2会发生什么.在那个catch块中我们抛出一个新的异常.
所以我调用myFunction的方法应该提供一些处理它的机制
myException?所以执行将转移到调用方法的catch块.对吗?
那么myFunction()的“finally”块会发生什么?它不会被执行呢?
如何进行程序流程?我真的很难发现当我们使用“throw”时会发生什么.我们使用它时会发生什么?
解决方法
请参阅(您的修改示例):
try { // Some code ... } catch(SomeException e1) { // SomeException code ... } catch(SomeOtherException e2) { // SomeOtherException is NOT SomeException extension throw new myException("whatever message required"); } finally { // Some final code ... }
执行可能性:
1. No exception at all: Some code executed Some final code executed 2. SomeException is thrown: Some code (may be partially) executed SomeException code executed Some final code executed 3. SomeOtherException is thrown: Some code (may be partially) executed Some final code executed throw new myException("whatever message required"); 4. SomeStrangeException is thrown Some code (may be partially) executed Some final code executed System'll look for other try {} catch {} block to catch SomeStrangeException
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。