尝试/捕获与抛出异常 [英] try/catch versus throws Exception

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

问题描述

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

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);
    }
}

推荐答案

是的,有很大的不同 - 后者吞下了异常(无可否认地显示它),而第一个将让它传播.(我假设 showException 不会重新抛出它.)

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.)

所以如果你调用第一个方法并且做某事"失败,那么调用者将不得不处理异常.如果你调用第二种方法并且做某事"失败,那么调用者根本不会看到异常......这通常是一件坏事,除非showException真正em> 处理异常,修复任何错误,并确保calculateArea 达到其目的.

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.

您将能够说出这一点,因为您无法在不捕获Exception自己声明的情况下调用第一个方法你的方法也可能会抛出它.

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.

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

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