How to tell Java compiler to not complain about certain exceptions not being caught or thrown?

exception, java

Solution

Assuming you mean checked exceptions, you can't. Typically I would catch the exception, but propagate it into a `RuntimeException`, e.g.

try {
   // Do something which could, but won't, throw SomeCheckedException
} catch (SomeCheckedException e) {
   throw new WorldHasGoneMadException(e);
}

You may very well want to create a specific exception for exactly this kind of scenario - while I wouldn't suggest `WorldHasGoneMadException` for the real name, something similar would be appropriate. This isn't just "something unexpected has happened" but "wow, I would have bet good money that this really, really couldn't happen".

Oh, and of course your unit tests won't cover this case. Live with it :)

Problem

Is there a way to tell the Java compiler to not complain about a certain exception not being caught or thrown if I am 100% sure that the exception will never occur?

Original source