Nimrod Nimrod - 4 months ago 6x
Java Question

Why one should try throw unchecked exception over checked exception?

I've been told that I should consider throwing Unchecked exception over Checked exception in my code and not only that, but to extend the RuntimeException with my own one.
Now, I do understand the difference between the two, but still doesn't understand why should I do that?

If I have this method header which throws 2 kinds of exceptions:

public static Optional<String> getFileMd5(String filePath) throws NoSuchAlgorithmException, IOException {}

Why should I replace them with one (less detailed) exception?


The IOException is acceptable. The caller can't be sure that the filePath exists and will still exist when the method is executed, and your method must be able to signal the problem. IOException is the conventional exception to throw in that case, although you could wrap it inside an UncheckedIOException if you prefer runtime exceptions. An unchecked IO exception would be as clear as a checked IOException. What you would lose (or gain, depending on the point of view) is that you wouldn't force the caller to deal with it.

The NoSuchAlgorithmException exception, on the other hand, should definitely be wrapped into an runtime exception. The caller has no way to do anything if your method uses an algorithm that doesn't exist. It's clearly a bug if that exception happens, and bugs should be signalled by runtime exceptions. So, write your own runtime exception, that wraps the original NoSuchAlgorithmException (so that you don't lose the root cause of the problem if you ever throw it), and don't bother all the callers of your code with an exception that should never, ever happen.

Regarding runtime vs. checked exceptions, it's mainly an opinion-based question, but a few things should be noted though:

  • AFAIK, no new Java API uses checked exceptions anymore. See java.time for example, which never throws checked exceptions although the old equivalent (like DateFormat) throws checked exceptions
  • Java is the only language to have checked exceptions.
  • Checked exceptions don't fit well with functional idioms (lambda expressions, streams, etc.) introduced in Java 8: No functional interface throws a checked exception.

I think it's safe to now say that checked exceptions were an interesting idea, but which proved to be a bad one. You should prefer unchecekd exceptions.

Now, if your question is: how to throw unchecked exceptions rather than checked exceptions, it's quite simple:

public static Optional<String> getFileMd5(String filePath) {
    try {
        // your original code
    catch (IOException e) {
        throw new UncheckedIOException(e);
    catch (NoSuchAlgorithmException e) {
        throw MyCustomCryptoException(e);