Search code examples
javatry-catcherror-suppression

Supress Java exeption if I know an exeption won't be thrown


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?


Solution

  • Unfortunately, no. You can't hide this exception.

    Since DateFormat.parse has throws ParseException, you need to catch in your code or add throws ParseException state for your method.

    The only exceptions you don't need to catch or add throws statement to make your program compile are exceptions that inherit RuntimeException.

    In your case ParseException doesn't inherit RuntimeException, so you need to catch it or use throws keyword.

    Sneaky throws approach

    Actually, you can fool Java compiler and sneaky throw checked exception.

    This can be achieved by the next method

    public static <E extends Throwable> void sneakyThrow(Throwable e) throws E {
        throw (E) e;
    }
    

    And then you can wrap an exception with this method

    try {
        Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2021-01-01")
    } catch (ParseExeption e) {
        sneakyThrow(e);
    }
    

    As you can see, it do require try/catch block, but you can use lombok library and it will do all the work for you with annotation @SneakyThrows.

    @SneakyThrows
    public void myMethod() {
        Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2021-01-01");
    }
    

    Code above will compile, but there is a requirement to use external library.