DEV Community

loading...
Cover image for Hide Checked Exceptions with SneakyThrows

Hide Checked Exceptions with SneakyThrows

Victor Rentea
Java Champion and Trainer, Associate Professor at University and ex-Lead Architect at IBM
Originally published at victorrentea.ro ・4 min read

Victor Rentea is a Java Champion and an Independent Trainer with a huge experience on topics like Clean Code, Design Patterns, Unit Testing. Find out more on victorrentea.ro.

Java is the only programming language in the world that has checked exceptions, which forces the caller to know about the individual exception types thrown by the called function.

What do you do when you face a checked exception? Propagating checked exceptions through your code is both leaking implementation details, annoying, and even dangerous. That's why in the vast majority of cases you should catch-rethrow it as a runtime exception, and let it "silently" terminate your current use-case.

This article introduces a "magic" way to generate that code that we wrote dozens/hundreds of times in our career. Here's a reminder:

public static Date parseDate(String dateStr) {
    try {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.parse(dateStr);
    } catch (ParseException e) {
        throw new RuntimeException(e); // this :(
    }
}
Enter fullscreen mode Exit fullscreen mode

If you are sick to do this catch-rethrow manually, here's the @SneakyThrows annotation coming from the magic realm of the Project Lombok.

Let's just annotate our method with it and simply remove the catch clause:

@SneakyThrows
public static Date parseDate(String dateStr) {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    return format.parse(dateStr);
}
Enter fullscreen mode Exit fullscreen mode

Doing so will instruct the Lombok annotation processor to hack the bytecode generated by the javac compiler, allowing the code above to compile, although there's no catch, nor throws clause for the ParseException.

Warning: the Java IDE you use must be hacked (see here how).

Knowing that Lombok is able to change your code as it’s compiled, one might expect that the current body of our function will be surrounded by

try { ... } catch (Exception e) { throw new RuntimeException(e); }
Enter fullscreen mode Exit fullscreen mode

That’s a fair expectation. Indeed, the checked exception is not swallowed but thrown back out of the function.

However, since Java8, Lombok does it in a bit unexpected way. To see what it really does, let's decompile the .class file:

public static Date parseDate(String dateStr) {
    try {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.parse(dateStr);
    } catch (Throwable var6) {
        throw var6;
    }
}
Enter fullscreen mode Exit fullscreen mode

Indeed, Lombok did add a try-catch block around the body of my function, but it caught a Throwable and rethrew it without wrapping it at all!

Something is wrong!

That Throwable must have been declared in a throws clause on the function!

If you copy-paste the code in a .java file, you’ll quickly see that this code doesn’t compile!! But how was it compiled in the first place?!

To understand how's that even possible, you have to learn that the distinction between checked and runtime exceptions is only enforced by the Java compiler (javac). The Java Runtime (JVM) does NOT care what kind of exception you throw - it propagates any exception down the call stack the same way. So the Lombok processor tricked javac into producing bytecode that represents code that wouldn’t actually be compilable.

Panic!
Alt Text

But a minute after you calm down, you get this strange thought: if the checked exception is invisibly thrown, how would you then be able to catch it later? Let's try:

try { 
    parseDate("2020-01-01"); 
} catch (ParseException e) {...}
Enter fullscreen mode Exit fullscreen mode

But this doesn't compile because nothing in the try block throws a ParseException. And javac will reject that. See for yourself: commit

So what does this mean? It means that the exceptions hidden using @SneakyThrows aren’t supposed to be caught again individually. Instead, a general catch (Exception) not ~catch (RuntimeException)~ should be in place somewhere down the call stack to catch the invisible checked exception. For example, if you are handling Spring REST endpoint exceptions using @RestControllerAdvice, make sure you declare to handle Exception.class. More details in an upcoming article.

Some of you might be disgusted at this point. Others might be super-excited. I’m not here to judge but only to report the techniques that have become wide-spread in the hundreds of projects I trained or consulted for. I agree that this can be misused if careless, so judge whether to use this feature responsibly.

Okay, okay... But why?!

Because Java is an old language. 25 years is a long time to carry some baggage. So today Lombok is effectively hacking the language to make us write less and more focused code.

Conclusion

  • Use Lombok's @SneakyThrows for fatal exceptions that you don't intend to selectively catch.
  • Otherwise wrap the checked exceptions in runtime exceptions that you throw instead.

Disclaimer: I chose on purpose parsing a date to point out a typically unrecoverable exception. You should definitely use the new Java 8 LocalDate/LocalDateTime API that (surprise!) doesn't throw any more checked exceptions, but runtime ones.

Discussion (2)

Collapse
michelemauro profile image
michelemauro

Worthy subject. There still is a lot of space for debate, and different codebases will need very different solutions.
Time ago I had a coworker who introduced some SneakyThrows use, but ultimately we felt it hindred debugging because sometimes an Exception was swallowed without a trace in the logs, and at development time it promoted an habit to check a method implementation for "sneakiness"...
The definitive solution to this problem is only the Either monad at API level. Everything else is just impedence adaptation.

Collapse
victorrentea profile image
Victor Rentea Author

Either (or vavr.Try) might be overkill to add everywhere for large codebases. It actually depends: if you are integrating with a system/library that throws a lot of checked exceptions at you, @SneakyThrows might not be a bad idea. On the other hand, using it just a few places it might indeed increase the risk, as people will probably be unaware of what it does and its hidden quirks.