在进行 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 block 中的代码 2.如果异常 e1 发生,那么它会在第一个 catch block 中被捕获,在那里进行适当的处理,然后最终 block 被执行。 3.但是如果出现异常e2会发生什么。在那个 catch block 中,我们抛出一个新的异常。 所以我调用 myFunction 的方法应该提供一些机制来处理这个 我的异常?所以执行会转移到调用方法的catch block ,对吧? 那么 myFunction() 的“finally” block 会发生什么?那它不会被执行吗? 程序流程是如何发生的?我真的很难发现当我们使用“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
关于java - 理解 JAVA 中的 throw 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23630428/