gpt4 book ai didi

java - EntityNotFoundException 应该扩展 Exception 还是 RuntimeException?

转载 作者:行者123 更新时间:2023-12-01 23:29:39 26 4
gpt4 key购买 nike

我的应用程序服务中有一个方法可以接收实体的id:

 Document doStuff(Long documentId);

在我的方法中,我检查传递的 id 是否与之前存储的实体匹配,如果不匹配,则会抛出异常。

现在,我的疑问是,这是com.application.exceptions.DocumentNotFoundExceptionRuntimeException还是Exception

服务是否应该强制谁使用它来管理 ID 错误的情况,还是隐式的?

最佳答案

作为引用:

enter image description here

运行时异常(未经检查的异常)

A RuntimeException class represents exceptions that occur within the Java virtual machine (during runtime). An example of a runtime exception is NullPointerException. The cost of checking for the runtime exception often outweighs the benefit of catching it. Attempting to catch or specify all of them all the time would make your code unreadable and unmaintainable. The compiler allows runtime exceptions to go uncaught and unspecified. If you like, you can catch these exceptions just like other exceptions. However, you do not have to declare it in your “throws" clause or catch it in your catch clause.

此外,您可以创建自己的 RuntimeException 子类,有时这种方法可能是首选,因为检查的异常会使方法变得复杂签名,并且可能很难遵循。

为什么不建议捕获类型“Exception”

Exception handling in Java is polymorphic in nature. For example if you catch type Exception in your code then it can catch or throw its descendent types like IOException as well. So if you catch the type Exception before the type IOException then the type Exception block will catch the entire exceptions and type IOException block is never reached. In order to catch the type IOException and handle it differently to type Exception, IOException should be caught first (remember that you can’t have a bigger basket above a smaller basket).

关于java - EntityNotFoundException 应该扩展 Exception 还是 RuntimeException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19536845/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com