ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

理解JAVA中的throw关键字

2019-07-28 14:00:52  阅读:145  来源: 互联网

标签: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块中的代码
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 

标签:java,exception,exception-handling,throw
来源: https://codeday.me/bug/20190728/1562551.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有