抛出私有异常有意义吗?

发布于 2024-10-21 23:10:21 字数 262 浏览 4 评论 0原文

我想抛出一个运行时异常,以防我的类不变量无效。由于这是一个编程错误(类似于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

醉酒的小男人 2024-10-28 23:10:21

您可以考虑使用现有的异常,除非您希望以不同的方式捕获该异常。如果预计不会捕获它,我认为不需要自定义异常。您可以重复使用一些异常

如果您想要自定义异常,您可以考虑扩展这些异常,或使用扩展这些异常的异常之一。

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

  • AssertionError - To me this means there is an unrecoverable programming error of an indeterminate type.
  • IllegalArgumentException - To me this means only of the arguments to the method was invalid.
  • IllegalStateException - To me this means the state of the object (e.g. combination of values) is not valid for this operation.

If you want a custom exception you may consider extending these exceptions, or using one of the exceptions which extend these.

衣神在巴黎 2024-10-28 23:10:21

我相信,为了抛出任何东西,该对象必须实现Throwable接口,这意味着它必须是Error或一个异常。由于您不希望您的客户端永远捕获该事件,因此您可能应该使用Error。来自 Error 文档

Error 是 Throwable 的子类
这表明存在严重问题
合理应用不应尝试
抓住。

这样您可能避免一些程序员倾向于使用的可怕的异常包罗万象 - 大多数时候这些程序员甚至不会考虑捕获错误 根本...

I believe that in order to throw anything, that object has to implement the Throwable interface, which meant that it has to be either an Error or an Exception. Since you don't want your clients to catch that event ever, you should probably use an Error. From the Error documentation:

An Error is a subclass of Throwable
that indicates serious problems that a
reasonable application should not try
to catch.

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 an Error at all...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文