你会永远抓不住异常,或者抛出不会被捕获的异常? [英] Would you ever NOT catch an exception, or throw an exception that won't be caught?

查看:672
本文介绍了你会永远抓不住异常,或者抛出不会被捕获的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经处理了情况,我会抛出/重新抛出异常知道周围的代码将捕捉特定异常。但是,有任何时候你想抛出一个异常,知道它不会被抓?

I've dealt with instances where I would throw/rethrow an exception knowing that the code surrounding it would catch the specific exception. But is there any time you would want to throw an exception, knowing that it wouldn't be caught?

或者至少不捕捉异常?

异常立即停止申请,除非他们处理吧?所以我想,我问你会不会想故意让你的应用程序死?

Exceptions immediately halt the application unless their handled right? So I guess I'm asking if you would ever want to purposely let your application die?

推荐答案

如果您的应用程序主要是去被其他客户端使用,而不是独立的,它通常是有道理的抛出异常,如果一个条件时,你不知道如何(或不愿)处理,而且也为你歇着没有明智的方法它。客户应该能够决定如何处理,你可能会引发任何异常。

If your application is primarily going to be used by other clients and is not standalone, it generally makes sense to throw exceptions if a condition arises that you don't know how to (or don't want to) handle, and there's no sensible way for you to recover from it. Clients should be able to decide how they want to handle any exceptions that you might throw.

在另一方面,如果你的应用程序的的了端点,抛出异常本质上变成一个通知机制,以提醒人们的东西实在过于离谱了。在这种情况下,你需要考虑以下几点:

On the other hand, if your application is the endpoint, throwing an exception essentially becomes a notification mechanism to alert people that something has gone terribly wrong. In such cases, you need to consider a few things:


  • 如何重要的是应用的持续运行?这是错误真的不可恢复?抛出异常,并终止你的程序是不是你想要的航天飞机是做什么的。

  • How important is the continued running of the application? Is this error really unrecoverable? Throwing an exception and terminating your program is not something you want to be doing on the space shuttle.

您使用的例外,真正记录一个代理有几乎没有理由这样做呢?;考虑一个真正的日志机制来代替。捕获该异常,并有记录的工作发生了什么。

Are you using exceptions as a proxy for real logging? There's almost never a reason to do this; consider a real logging mechanism instead. Catch the exception and have the logger work out what happened.

什么是你想通过抛出异常来传达自己?问自己什么抛出一个新的异常值,并仔细考虑是否有没有更好的方法去做你想做的。

What are you trying to convey by throwing the exception yourself? Ask yourself what the value in throwing a new exception is, and consider carefully whether there isn't a better way to do what you want.

不捕获异常可能会在一个糟糕的状态,离开资源。如果您没有正常退出,事情一般不会清理你。请确保你知道你在做什么,如果你需要做到这一点 - 如果你不打算抓住它,至少考虑一个尝试,终于块,你可以做一些整理。

Not catching an exception may leave resources in a bad state. If you don't gracefully exit, things are generally not cleaned up for you. Make sure you understand what you're doing if you need to do this -- and if you're not going to catch it, at least consider a try-finally block so you can do some tidying up.

这篇关于你会永远抓不住异常,或者抛出不会被捕获的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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