{"id":13204,"date":"2017-10-01T17:26:15","date_gmt":"2017-10-01T15:26:15","guid":{"rendered":"https:\/\/touk.pl\/blog\/?p=13204"},"modified":"2022-08-02T13:00:40","modified_gmt":"2022-08-02T11:00:40","slug":"sneakily-throwing-exceptions-in-lambda-expressions-in-java","status":"publish","type":"post","link":"https:\/\/touk.pl\/blog\/2017\/10\/01\/sneakily-throwing-exceptions-in-lambda-expressions-in-java\/","title":{"rendered":"Sneakily Throwing Exceptions in Lambda Expressions in Java"},"content":{"rendered":"<p>Handling checked exceptions in lambda expressions is often frustrating. Luckily, there is a type inference rule that we can exploit\u2026<!--more--><\/p>\n<h2 id=\"java-8-type-inference\">Java 8 Type-Inference<\/h2>\n<p>While reading through the <a href=\"http:\/\/docs.oracle.com\/javase\/specs\/jls\/se8\/html\/jls-18.html\">Java Language Specification<\/a>, we can find an interesting information:<\/p>\n<blockquote><p>A bound of the form \u201c<em>throws \u03b1<\/em>\u201d is purely informational: it directs resolution to optimize the instantiation of \u201c<em>\u03b1\u201d<\/em> so that, if possible, it is not a checked exception type. (\u2026) Otherwise, if the bound set contains \u201cthrows \u03b1i\u201d, and the proper upper bounds of \u201c\u03b1i\u201d are, at most, Exception, Throwable, and Object, then Ti = RuntimeException. <strong>Which simply means that every <em>\u201cthrows<\/em> <em>T<\/em>\u201d will be generously inferred to a <em>RuntimeException.<\/em><\/strong><\/p><\/blockquote>\n<p>This was originally intended to e.g. solve the ambiguous problem of inferring checked exceptions from empty lambda expression bodies.<\/p>\n<p>And now, it\u2019s possible to exploit that rule and create a util method that will allow us to rethrow checked exceptions behind compiler\u2019s back using a little trick:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">@SuppressWarnings(\"unchecked\")\r\nstatic <T extends Exception, R> R sneakyThrow(Exception t) throws T {\r\n    throw (T) t; \/\/ ( \u0361\u00b0 \u035c\u0296 \u0361\u00b0)\r\n}<\/pre>\n<p>And indeed \u2013 the following works as <del>un<\/del>expected:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">sneakyThrow(new IOException());<\/pre>\n<p>The boundary line between checked and unchecked exceptions does not exist at runtime, so everything works normally.<\/p>\n<h2 id=\"unchecked-lambda-expressions\">Unchecked Lambda Expressions<\/h2>\n<p>Since it\u2019s possible to rethrow checked exceptions as unchecked, why not use this approach for minimizing the amount of boilerplate used when dealing with aching exceptions present in lambda expressions\u2019 bodies?<\/p>\n<p>First, we\u2019d need a functional interface that represents a function that throws an <em>Exception:<\/em><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">public interface ThrowingFunction<T, R> {\r\n    R apply(T t) throws Exception;<\/pre>\n<p>And now we could write an adapter method for converting it to the <em>java.util.function.Function<\/em> instance:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">static <T, R> Function<T, R> unchecked(ThrowingFunction<T, R> f)<\/pre>\n<p>Inside the implementation, we\u2019d simply create a new lambda that delegates the job to the old one but rethrows the exception in case it\u2019s raised:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">static <T, R> Function<T, R> unchecked(ThrowingFunction<T, R> f) {\r\n    return t -> {\r\n        try {\r\n            return f.apply(t);\r\n        } catch (Exception ex) {\r\n            return ThrowingFunction.sneakyThrow(ex);\r\n        }\r\n    };\r\n}<\/pre>\n<p>And now, we no longer need to try-catch exceptions in lambda expressions:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">Optional.of(42)\r\n  .map(i -> {\r\n      try {\r\n          return throwException(i);\r\n      } catch (IOException e) {\r\n          e.printStackTrace();\r\n          return null;\r\n      }\r\n  });<\/pre>\n<p>And we can simply write:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">Optional.of(42)\r\n  .map(unchecked(ThrowingFunctionTest::throwException));<\/pre>\n<h2 id=\"the-other-edge\">The Other Edge<\/h2>\n<p>As expected, Sneaky Throws is a double-edged sword.<\/p>\n<blockquote><p>Just because you don\u2019t like the rules, doesn\u2019t mean its a good idea to take the law into your own hands. Your advice is irresponsible because it places the convenience of the code writer over the far more important considerations of transparency and maintainability of the program. \u2013 Brian Goetz (<a href=\"https:\/\/stackoverflow.com\/questions\/19757300\/java-8-lambda-streams-filter-by-method-with-exception\">source<\/a>)<\/p><\/blockquote>\n<p>Besides the danger of having a leakage of exceptions, we can\u2019t catch exceptions using their type because of javac\u2019s \u201chelping\u201d hand which is a clear loss of flexibility:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">try {\r\n    sneakyThrow(new IOException());\r\n} catch (IOException e) { \/\/ exception is never thrown in corresponding try block\r\n    e.printStackTrace();\r\n}<\/pre>\n<h2 id=\"summary\">Summary<\/h2>\n<p>The concept of sneaky throws has been around for a couple of years but with a new Type Inference rule, it became much cleaner to execute \u2013 which can be particularly handy when dealing with exceptions and lambda expressions but it has its <a href=\"https:\/\/quoteinvestigator.com\/2015\/07\/23\/great-power\/\">price<\/a>.<\/p>\n<p>A number of libraries utilize this approach. For example, <a href=\"https:\/\/projectlombok.org\/features\/SneakyThrows\">Lombok<\/a> and <a href=\"http:\/\/www.vavr.io\">Vavr<\/a>.<\/p>\n<p>Code snippets <a href=\"https:\/\/github.com\/pivovarit\/articles\/tree\/master\/sneaky-throws-lambda\">can be found on GitHub.<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"Handling checked exceptions in lambda expressions is often frustrating. Luckily, there is a type inference rule that we&hellip;\n","protected":false},"author":68,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11],"tags":[],"class_list":{"0":"post-13204","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-development-design"},"_links":{"self":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/13204","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/users\/68"}],"replies":[{"embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/comments?post=13204"}],"version-history":[{"count":13,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/13204\/revisions"}],"predecessor-version":[{"id":14834,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/13204\/revisions\/14834"}],"wp:attachment":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/media?parent=13204"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/categories?post=13204"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/tags?post=13204"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}