{"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&#8230;<!--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 &#8220;<em>throws \u03b1<\/em>&#8221; is purely informational: it directs resolution to optimize the instantiation of &#8220;<em>\u03b1&#8221;<\/em> so that, if possible, it is not a checked exception type. (&#8230;) Otherwise, if the bound set contains &#8220;throws \u03b1i&#8221;, and the proper upper bounds of &#8220;\u03b1i&#8221; are, at most, Exception, Throwable, and Object, then Ti = RuntimeException. <strong>Which simply means that every <em>&#8220;throws<\/em> <em>T<\/em>&#8221; 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&#8217;s possible to exploit that rule and create a util method that will allow us to rethrow checked exceptions behind compiler&#8217;s back using a little trick:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">@SuppressWarnings(\"unchecked\")\r\nstatic &lt;T extends Exception, R&gt; R sneakyThrow(Exception t) throws T {\r\n    throw (T) t; \/\/ ( \u0361\u00b0 \u035c\u0296 \u0361\u00b0)\r\n}<\/pre>\n<p>And indeed &#8211; 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&#8217;s 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&#8217; bodies?<\/p>\n<p>First, we&#8217;d 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&lt;T, R&gt; {\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 &lt;T, R&gt; Function&lt;T, R&gt; unchecked(ThrowingFunction&lt;T, R&gt; f)<\/pre>\n<p>Inside the implementation, we&#8217;d simply create a new lambda that delegates the job to the old one but rethrows the exception in case it&#8217;s raised:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">static &lt;T, R&gt; Function&lt;T, R&gt; unchecked(ThrowingFunction&lt;T, R&gt; f) {\r\n    return t -&gt; {\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 -&gt; {\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&#8217;t like the rules, doesn&#8217;t 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. &#8211; 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&#8217;t catch exceptions using their type because of javac&#8217;s &#8220;helping&#8221; 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 &#8211; 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}]}}