加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

理解JAVA中的throw关键字

发布时间:2020-12-15 04:20:12 所属栏目:Java 来源:网络整理
导读:在JAVA中进行异常处理练习时,我对各种事情感到困惑.基本上我不明白的是当遇到异常时程序的流程如何.我想了解程序的流程实际上是如何在以下场景中进行的,以及我对这些概念的理解是对还是错. public void myFunction(){ try{ //Some code...... }catch(Excepti
在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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读