Hide Checked Exceptions with SneakyThrows
Tags: exceptions, java, cleancode, lombok
Published: 2020-12-25 05:33:28

_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](https://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 :(
	}
}
```

If you are sick to do this catch-rethrow manually, here's the `@SneakyThrows` annotation coming from the magic realm of the [Project Lombok](https://projectlombok.org/features/SneakyThrows).

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, although there's no `catch`, nor `throws` clause for the `ParseException`.

> **Warning**: the Java IDE you use must be hacked (see [here](https://projectlombok.org/setup/overview) 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!
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/d9l65tvt957g47qcycbh.png)

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](https://github.com/victorrentea/exceptions-guide/commit/aa1ba41cb1b7694ebb087bd405b7580b572b8ab2)

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](presenting-exceptions-to-users).

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.