try / catch与throws异常 [英] try/catch versus throws Exception

查看:128
本文介绍了try / catch与throws异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些代码语句是否等同?
他们之间有什么区别吗?

  private void calculateArea()throws Exception {
... .do something
}






  private void calculateArea(){
try {
.... do something

} catch(Exception e){
showException E);
}
}


解决方案

是有一个巨大的差异 - 后者吞噬了例外(显而易见),而第一个会让它传播。 (我假设 showException 不重写它。)



所以如果你调用第一个方法做某事失败,那么调用者将不得不处理异常。如果你调用第二种方法并且做某事失败,那么调用者根本看不到异常,这通常是一件坏事,除非 showException 真正地处理异常,修正了错误,并且一般都确保 calculateArea 已经实现了目的。



你可以告诉这一点,因为你不能调用第一种方法,不用 捕捉异常你自己声明您的方法也可能会抛出。


Are these code statements equivalent? Is there any difference between them?

private void calculateArea() throws Exception {
        ....do something
    }


private void calculateArea() {
        try {
            ....do something

        } catch (Exception e) {
            showException(e);
        }
    }

解决方案

Yes, there's a huge difference - the latter swallows the exception (showing it, admittedly), whereas the first one will let it propagate. (I'm assuming that showException doesn't rethrow it.)

So if you call the first method and "do something" fails, then the caller will have to handle the exception. If you call the second method and "do something" fails, then the caller won't see an exception at all... which is generally a bad thing, unless showException has genuinely handled the exception, fixed whatever was wrong, and generally made sure that calculateArea has achieved its purpose.

You'll be able to tell this, because you can't call the first method without either catching Exception yourself or declaring that your method might throw it too.

这篇关于try / catch与throws异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆