Java Exception Handling – Checked vs Unchecked Exceptions

exception handlingjava

I have a service that allow users to add dynamic content to a repository. So basically I have a generic Document class that contains a list of property for that specific object depending on what type of document the user is adding (eg. an invoice document has an invoice number property while a wiki document has an author property, and so on).

The service is comprised of different layers and at some point I have a class that has to check if the document to be added is compliant to the rules configurer, evaluating if all required properties are provided, if they are all of the right type, etc. If any of these validations fail I want to throw a custom exception which contains the validation status.

The question is:

  • Should my ValidationException be checked or unchecked?

I read a lot of best practice on how to decide what kind of exception use. I was thinking about using RuntimeException but in this case the exception is not caused by error in coding or stuff like that but just by the user input…

On the other hand using a checked exception would mean to propagate the "throws" syntax in all the above layer of the application and probably in the 90% of the service's methods making the code much less readable and maintainable.

Best Answer

I think Oracle docs can't be more explicit about it:

Generally speaking, do not throw a RuntimeException or create a subclass of RuntimeException simply because you don't want to be bothered with specifying the exceptions your methods can throw.

Here's the bottom line guideline: 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.

Source here...

You are the only one who knows if this is the case.

I believe that the real problem is not whether it should be a checked or an unchecked exception, but the many levels you would have to propagate the checked exception (as you said) for it to be properly handled. Perhaps you could tell us a little bit more about your design.

Related Topic