简体   繁体   中英

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. However, I have seen people writing custom exception which extends 'RuntimeException' class making it an unchecked exception.

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. 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). Otherwise you'd make it a RuntTimeException, and again, we'd need to know what you want to do specifically. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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