Hide Checked Exceptions with SneakyThrows

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? As we will see in a later blog post, 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 :(
    }
}

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);
}

Doing so will instruct the Lombok annotation processor to hack the bytecode generated by the javac compiler, allowing the code above to compile, altough 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); }

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;
    }
}

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! file

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) {...}

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.

And here's a post about the topic of whether or not to use Lombok in your Java project.

Popular Posts

10 Comments

  1. Excellent Post. Very informative hack!! Thanks for sharing.

  2. Great article. Thanks. You’ve touched upon this topic in one of your previous talks and it’s a pity it wasn’t recorded. Lot of useful tips there.

    1. In january at jchampions conference it will bevrecorded.

    2. hello victor,
      what do you think of this library:
      https://github.com/diffplug/durian

  3. hello victor,
    what do you think of this library:
    https://github.com/diffplug/durian

    1. Less stars on github (1/6), newer and aiming to do much more than just Unchecked and Seq, as jool.

      I donno…

      But clearly not agains either.

  4. Hello Victor! Thank you for the article. We just have been arguing in the team about Lombok. Some people love it but some people don’t. I have mixed feelings about Lombok. I use @Data @Getter @Builder annotations. But I can work without them. And I don’t use @SneakyThrows annotation and others. I think Lombok is a bit overvalued library. It is useful but it brings problems too. One member of our team uses the NetBeans IDE and the last version doesn’t have an “annotation processing” option. He has some problems. I had one more problem – @ToString() + hibernate lazy collection. You should add lazy fields as excluded to your @ToString annotation. And If you use @Data in the entity @Data brings @ToString annotation too. In other words – Lomok brings new rules, hacks, errors to your projects. Any additional library brings new bugs. What about clean code? I think the code with @SneakyThrows not really clean. I prefer the boilerplate code in this case. Honestly. I don’t like annotation-driven development like this. Can you share your thoughts about Lombok in general in future articles?

    1. Yes, lombok does raise some problems. I talked about some best practices of using it here: https://youtu.be/DaOmyyRA8VU

      But here are some quick points:
      – NetBeans??
      – @ToString and hashCode equals should not be blindly added to hibernate Entities. One workaround: https://projectlombok.org/features/ToString you can exclude the collection fields, or selectively include only the relevant attributes. Works both in ToString as in HashCodeEquals.
      – Actually, I would try to avoid @Data on an @Entity altogether.
      – I am perfectly fine with NOT using Lombok, but it usually happens that a battle-hardened Java developer team gets sick of the boilerplate the 25-years old Java language has us writing, and then they search for options. In those cases, I would encourage the team to start using Lombok.
      – @SneakyThrows is a piece of magic that I would recommend adding only after ~1y of active use of Lombok in your project, after you are comfortable with the other simpler code-generation annotations.

      But indeed, Lombok is NOT a requirement for Clean Code.

  5. Thank you for the post. Is it the broken link (blog post) in the fraze “As we will see in a later blog post” ?

    1. Well, it does say “later post” right? 😀 I’m currently editing that. I’ll post it in a couple of weeks.

Leave a Reply to Sourav Dalal Cancel reply

Your email address will not be published. Required fields are marked *