java - 理解 JAVA 中的 throw 关键字

标签 java exception exception-handling throw

在进行 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/

相关文章:

java - 安装新的 tomcat 服务器 (5.5) 时出现错误消息

php - 我们需要 PHP 异常代码做什么?任何用例场景?

python - 'finally' 字的 Jython 语法错误

Java REST 响应值缺少拼写字符

java - Mongo Hadoop 连接器问题

java - 如何以编程方式将 Android root 设备中的 .raw 文件转换为图像文件

java - Scala future 和 `andThen` 异常传播

c++ - boost::exception 和 std::exception 之间的关系

C++ - 捕获双重异常

java - OutputStream 代码没有给出任何错误,但 txt 文件丢失