Search code examples
javaexceptionchecked-exceptionsunchecked-exception

How do you judge whether to make an exception checked or unchecked?


I was reading about checked vs unchecked exceptions in Java and when to use each:

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

An example of something a client can't be expected to recover from is divide by zero, where something they can recover from is a FileNotFound exception. I don't see the difference yet though. Why can you catch one and log an error but not catch the other and log the error? What makes something reasonably recoverable? Can't you catch an error (thus recovering) in all circumstances?


Solution

  • The meaning of the quote is this: If the client code can not recover from the problem, it needs to let the exception propagate to higher layers. If you use checked exceptions for that, you need to declare the checked exception through all call layers without benefit.

    To rephrase the quote: If the exception is expected to propagate through the layers, make it unchecked. Only make it checked if the caller can actually do something about it.