简体   繁体   English

自定义异常应该是检查异常或运行时异常

[英]Custom Exception should be a checked exception or Runtime exception

I usually write my custom exception by inheriting the 'Exception' class which makes it a checked exception. 我通常通过继承'Exception'类来编写自定义异常,这使它成为受检查的异常。 However, I have seen people writing custom exception which extends 'RuntimeException' class making it an unchecked exception. 但是,我见过人们在编写自定义异常,该异常扩展了'RuntimeException'类,使其成为未经检查的异常。

Which is the best practice and when to use which one? 最佳做法是什么,何时使用?

There's nothing wrong, per-se, in either approach, and it very much depends on your usecase. 每种方法本质上都没有错,这在很大程度上取决于您的用例。

Having said that, one of the common reasons to have a custom exception hierarchy is so you're able to intelligently catch them and react accordingly, while using runtime exceptions usually means you have no desire or intention to catch them. 话虽如此,拥有自定义异常层次结构的常见原因之一是,您能够智能地捕获它们并做出相应的反应,而使用运行时异常通常意味着您无意或无意捕获它们。

There is not an specific rule for this, just keep this in mind: If a client can reasonably be expected to recover from an exception, make it a checked exception. 对此没有特定的规则,只需记住以下几点:如果可以合理地期望客户端从异常中恢复,请将其设置为已检查的异常。 If a client cannot do anything to recover from the exception, make it an unchecked exception. 如果客户端无法采取任何措施来从异常中恢复,请将其设置为未经检查的异常。

The Java language gives you the power to decide. Java语言使您能够做出决定。 If there's no way for a program you create to compile, you'd typically make it a checked exception (although Java would do this for you in most cases and i'd need to know specifically what you are trying to do if you don't want to program to be able to compile which could be complex). 如果您创建的程序无法编译,通常会使其成为受检查的异常(尽管在大多数情况下Java会为您执行此操作,如果您不这样做,我将需要明确地知道您要做什么。希望程序能够编译,这可能很复杂。 Otherwise you'd make it a RuntTimeException, and again, we'd need to know what you want to do specifically. 否则,您将使它成为RuntTimeException,并且再次,我们需要知道您要具体执行的操作。 In my personal experience, if i'm making a custom exception, I'll simply make it a checked exception because users understand how my program operates, and (or I understand how it operates well enough to know when there could be an issue). 以我的个人经验,如果我要创建自定义异常,我将其简单地设为受检查的异常,因为用户了解我的程序如何运行,并且(或者我了解它的运行情况足以知道何时可能出现问题)。 。 For that reason, I err on the side of checked exceptions so that anyone who reuses my code easily understands how it works and where potential errors my arise. 因此,我会在检查异常的一边犯错,以便任何重用我的代码的人都可以轻松理解它的工作方式以及潜在的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM