Search code examples
javaexceptionchecked-exceptionsunchecked-exception

Always Use Checked Exceptions


I have been re-factoring some Java code lately... I have found that there were many RuntimeExceptions being thrown (i.e. unchecked exceptions). I have created my own checked exception and replaced each instance of these RuntimeExceptions with my own exception. Then, this forced me to check the exceptions.

With that said, I find checked exceptions better because another developer will make sure to handle the exceptions... Instead of the program just eating the exception without displaying anything to the user.

I have read many articles on unchecked vs. checked exceptions.. However, I still feel like I checked exceptions more because it reduces human error.

How poor of programming is it too mainly use checked exceptions? Has anyone else felt like they like checked exceptions more than unchecked exceptions?


Solution

  • my recommendation, although different people will have different opinions about this, is to:

    • use checked exceptions for exceptional conditions that should be handled by what you consider part of your application logic, e.g: user typed in a non existing user name to log in, user tried to save and item beyond the limit allowed for her subscription, etc. That way the client of the code that finds the exceptional condition is forced to at least acknowledge the fact that the condition might occur and hopefully will handle it in the most appropriate way
    • use unchecked exceptions to fail early and noisily under circumstances not under your control and from which you cannot recover with application logic, e.g: your function receives the wrong parameters as arguments: sounds like the perfect scenario to throw an 'illegal argument exception', which is a runtime exception in most of programming languages out there