Search code examples
javaexceptionlombokchecked-exceptionsintellij-lombok-plugin

Application of @Sneaky Throws in lombok


I was playing with the Lombok library in Java and found an annotation called @SneakyThrows. As the documentation states:

@SneakyThrows fakes out the compiler. In other words, Lombok doesn't wrap or replace the thrown checked exception, but makes the compiler think that it is an unchecked exception.

With other words, this is a way to bypass exceptions at compile time. But in my opinion this should not be the correct way of handling exceptions, because the bypassed exception can show weird behaviour at runtime.

So in which scenario should @SneakyThrows be used?


Solution

  • To add to the existing answers. I personally dislike checked exceptions. See for more info: https://phauer.com/2015/checked-exceptions-are-evil/

    To add insult to injury, the code gets bloated when avoiding the checked exceptions. Consider the usage of @SneakyThrows:

     List<Instant> instantsSneaky = List.of("2020-09-28T12:30:08.797481Z")
            .stream()
            .map(Example::parseSneaky)
            .collect(Collectors.toList());
    
    @SneakyThrows
    private static Instant parseSneaky(String queryValue) {
        return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(queryValue).toInstant();
    }
    

    versus non-@SneakyThrows

     private static Instant parseNonSneaky(String queryValue) throws ParseException {
        return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(queryValue).toInstant();
    }
    
    List<Instant> instantsNonSneaky = List.of("2020-09-28T12:30:08.797481Z")
            .stream()
            .map(timeStamp -> {
                try {
                    return parseNonSneaky(timeStamp);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            })
            .collect(Collectors.toList());
    

    Hence the applicance of @SneakyThrows enables much cleaner code.