抛出私有异常有意义吗?
我想抛出一个运行时异常,以防我的类不变量无效。由于这是一个编程错误(类似于 NullPointerException),因此客户端不应捕获该异常。
异常类应该声明为私有还是公共(或其他)?
class Foo
{
// ...
private static class InvariantsViolated
{
// ...
}
}
是否有关于自定义运行时异常和可见性的指南?
I want to throw a runtime exception in case my class invariants are invalidated. Since this is a programming error (similar to a NullPointerException), clients should not catch that exception.
Should the exception class be declared private or public (or something else)?
class Foo
{
// ...
private static class InvariantsViolated
{
// ...
}
}
Are there any guidelines on custom runtime exceptions and visibility?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以考虑使用现有的异常,除非您希望以不同的方式捕获该异常。如果预计不会捕获它,我认为不需要自定义异常。您可以重复使用一些异常
如果您想要自定义异常,您可以考虑扩展这些异常,或使用扩展这些异常的异常之一。
You may consider using an existing exception unless you expect this exception to be caught in a different way. If it is not expected to be caught, I don't see the need for a custom exception. Some exceptions you could re-use
If you want a custom exception you may consider extending these exceptions, or using one of the exceptions which extend these.
我相信,为了
抛出
任何东西,该对象必须实现Throwable
接口,这意味着它必须是Error
或一个异常
。由于您不希望您的客户端永远捕获该事件,因此您可能应该使用Error
。来自Error
文档:这样您可能避免一些程序员倾向于使用的可怕的
异常
包罗万象 - 大多数时候这些程序员甚至不会考虑捕获错误
根本...I believe that in order to
throw
anything, that object has to implement theThrowable
interface, which meant that it has to be either anError
or anException
. Since you don't want your clients to catch that event ever, you should probably use anError
. From theError
documentation:That way you may avoid the dreaded
Exception
catch-alls some programmers tend to use - most times these programmers don't even think about catching anError
at all...