Java编程中异常处理的特殊情况
1、不能在finally块中执行return,continue等语句,否则会把异常“吃掉”;
2、在try,catch中如果有return语句,则在执行return之前先执行finally块
请大家下面的例子:
[iocblog.net 来源]
[iocblog.net 来源]
- public class trytest {
- public static void main(string[] args) {
- try {
- system.out.println(trytest.test());// 返回结果为true其没有任何异常
- } catch (exception e) {
- system.out.println("exception from main");
- e.printstacktrace();
- }
- dothings(0);
- }
- public static boolean test() throws exception {
- try {
- throw new exception("something error");// 第1步.抛出异常
- } catch (exception e) {// 第2步.捕获的异常匹配(声明类或其父类),进入控制块
- system.out.println("exception from e");// 第3步.打印
- return false;// 第5步. return前控制转移到finally块,执行完后再返回(这一步被吃掉了,不执行)
- } finally {
- return true; // 第4步. 控制转移,直接返回,吃掉了异常
- }
- }
- public static void dothings(int i)
- {
- try
- {
- if(i==0)
- {
- //在执行return之前会先执行finally
- return;
- }
- int t=100/i;
- system.out.println(t);
- }catch(exception ex)
- {
- ex.printstacktrace();
- }
- finally
- {
- system.out.println("finally");
- }
- }
- }
Tag: 异常处理
文章整理:iocblog
版权申明:本站文章均来自网络,如有侵权,请联系我们,我们收到后立即删除,谢谢!
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。