How to tell the Java compiler not to complain about some exceptions that were not caught or thrown?

Is there any way to tell the Java compiler not to complain that some exception will not be caught or thrown if I am 100% sure that the exception will never happen?

+3
source share
3 answers

Assuming you mean checked exceptions, you cannot. Usually I get an exception, but extend it to RuntimeException, for example.

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

- WorldHasGoneMadException , - . "- ", " , , , ".

, , , . :)

+10

, Jon answer , assert, WorldHasGoneMadException, .

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

. AssertionErrors, , . , ( , , ?) .

+5

If there is a parameter that I'm sure not, I would not recommend using it.

I usually encounter "never happen" events when debugging a production error where it happened. ;-) At least I would suggest trying / catching with some level of ERROR logging so that at least you find out about the problem in the odd case where this really happens.

Hope this helps.

+2
source

All Articles