Is it possible to supress an exeption in a Java code? Suppose I'm trying to do something as basic as this:
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2021-01-01")
The .parse() method throws an exeption in case the string is in an incorrect format, so a try-catch block is necessary:
try {
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2021-01-01")
} catch (ParseExeption e) {
//Nothing to do here
}
However, I know for a fact that an exeption won't be thrown. Is there a way to avoid the use of the try-catch block?
Unfortunately, no. You can't hide this exception.
Since
DateFormat.parsehasthrows ParseException, you need to catch in your code or addthrows ParseExceptionstate for your method.The only exceptions you don't need to catch or add
throwsstatement to make your program compile are exceptions that inheritRuntimeException.In your case
ParseExceptiondoesn't inheritRuntimeException, so you need to catch it or usethrowskeyword.Sneaky throws approach
Actually, you can fool Java compiler and sneaky throw checked exception.
This can be achieved by the next method
And then you can wrap an exception with this method
As you can see, it do require
try/catchblock, but you can use lombok library and it will do all the work for you with annotation@SneakyThrows.Code above will compile, but there is a requirement to use external library.