{"id":1020,"date":"2010-02-03T22:39:26","date_gmt":"2010-02-03T21:39:26","guid":{"rendered":"http:\/\/www.gamlor.info\/wordpress\/?p=1020"},"modified":"2021-03-11T09:45:22","modified_gmt":"2021-03-11T08:45:22","slug":"throwing-checked-excpetions-like-unchecked-exceptions-in-java","status":"publish","type":"post","link":"https:\/\/www.gamlor.info\/wordpress\/2010\/02\/throwing-checked-excpetions-like-unchecked-exceptions-in-java\/","title":{"rendered":"Throwing Checked Exceptions Like Unchecked Exceptions in Java"},"content":{"rendered":"<p>\u00a0<\/p>\n<div id=\"attachment_1023\" style=\"width: 310px\" class=\"wp-caption alignright\"><a href=\"https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/2010\/02\/java-fool-checked-exceptions.png\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-1023\" class=\"size-medium wp-image-1023\" title=\"java-fool-checked-exceptions\" src=\"https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/2010\/02\/java-fool-checked-exceptions-300x241.png\" alt=\"Fooling Checked=\" width=\"300\" height=\"241\" srcset=\"https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/2010\/02\/java-fool-checked-exceptions-300x241.png 300w, https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/2010\/02\/java-fool-checked-exceptions.png 600w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/a><p id=\"caption-attachment-1023\" class=\"wp-caption-text\">Fooling Checked Exceptions<\/p><\/div>\n<p>Everyone who\u2019s programming Java knows checked exceptions. You only can throw a checked exception when you\u2019ve declare it. And you have to catch an checked exception, no matter whether it actually can occur.<\/p>\n<p>First my opinion: I think check exception are a failure. The intention was good, but in practice they cause pain, boilerplate-code and in general cause more problems than they solve.<\/p>\n<p>So in my code I avoid checked exceptions. Unfortunately the existing JAVA-API\u2019s are littered with checked exceptions. So I still need to deal with them. The usual strategy looks like this:<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">try<\/span>{\r\n     someObject.doOperation();\r\n} <span class=\"kwrd\">catch<\/span>(OperationException e){\r\n    <span class=\"kwrd\">throw<\/span> <span class=\"kwrd\">new<\/span> RuntimeException(<span class=\"str\">\"See inner exception\"<\/span>,e);\r\n}<\/pre>\n<p>This works fine, but fills up the stack-trace with unnecessary garbage. (grey= garbage, black= important). And because you normally have multiple such rethrow-blocks in your code, the cause is nested somewhere in a huge stack trace:<\/p>\n<pre class=\"csharpcode\"><span style=\"color: #808080;\">Exception in thread \"main\" java.lang.RuntimeException: See inner exception\r\n    at ch.gamlor.test.ExceptionBlogPost.methodWithoutCheckedException(ExceptionBlogPost.java:27)\r\n    at ch.gamlor.test.ExceptionBlogPost.openSimulation(ExceptionBlogPost.java:20)\r\n    at ch.gamlor.test.ExceptionBlogPost.demostrateStackTrace(ExceptionBlogPost.java:15)\r\n    at ch.gamlor.test.ExceptionBlogPost.main(ExceptionBlogPost.java:11)<\/span>\r\nCaused by: ch.gamlor.test.OperationFailedException: Could not find appropriate example\r\n    at ch.gamlor.test.ExceptionBlogPost.legacyMethodWithCheckedExceptions(ExceptionBlogPost.java:32)\r\n    at ch.gamlor.test.ExceptionBlogPost.methodWithoutCheckedException(ExceptionBlogPost.java:25)\r\n    ... 3 more<\/pre>\n<h3>The Hack<\/h3>\n<p>Now recently I\u2019ve discovered this <a href=\"http:\/\/stackoverflow.com\/questions\/15496\/hidden-features-of-java\">post on StackOverflow<\/a>, about unknown \u2018features\u2019 of the Java language. There someone <a href=\"http:\/\/stackoverflow.com\/questions\/15496\/hidden-features-of-java\/2131355#2131355\">showed how to throw checked exception without declaring them<\/a>. Basically he combines the exception with generics and misuses the <a href=\"http:\/\/en.wikipedia.org\/wiki\/Generics_in_Java#Type_erasure\">type erasure of the compiler<\/a>, so that the type of the exception is erased =). Btw. the post includes another surprise: You can declare a class in methods =).<\/p>\n<p>Here\u2019s the code and more details how it works:<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">public<\/span> final <span class=\"kwrd\">class<\/span> UncheckedThrow {\r\n    <span class=\"kwrd\">private<\/span> UncheckedThrow(){}\r\n\r\n    <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">static<\/span> <span class=\"kwrd\">void<\/span> throwUnchecked(final Exception ex){\r\n        <span class=\"rem\">\/\/ Now we use the 'generic' method. Normally the type T is inferred<\/span>\r\n        <span class=\"rem\">\/\/ from the parameters. However you can specify the type also explicit!<\/span>\r\n        <span class=\"rem\">\/\/ Now we du just that! We use the RuntimeException as type!<\/span>\r\n        <span class=\"rem\">\/\/ That means the throwsUnchecked throws an unchecked exception!<\/span>\r\n        <span class=\"rem\">\/\/ Since the types are erased, no type-information is there to prevent this!<\/span>\r\n        UncheckedThrow.&lt;RuntimeException&gt;throwsUnchecked(ex);\r\n    }\r\n\r\n    <span class=\"rem\">\/**<\/span>\r\n<span class=\"rem\">     * Remember, Generics are erased in Java. So this basically throws an Exception. The real<\/span>\r\n<span class=\"rem\">     * Type of T is lost during the compilation<\/span>\r\n<span class=\"rem\">     *\/<\/span>\r\n    <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">static<\/span> &lt;T extends Exception&gt; <span class=\"kwrd\">void<\/span> throwsUnchecked(Exception toThrow) throws T{\r\n        <span class=\"rem\">\/\/ Since the type is erased, this cast actually does nothing!!!<\/span>\r\n        <span class=\"rem\">\/\/ we can throw any exception<\/span>\r\n        <span class=\"kwrd\">throw<\/span> (T) toThrow;\r\n    }\r\n}<\/pre>\n<p>Now you just can use this method to \u2018rethrow\u2019.:<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">try<\/span>{\r\n    legacyMethodWithCheckedExceptions();\r\n} <span class=\"kwrd\">catch<\/span> (OperationFailedException e){\r\n    UncheckedThrow.throwUnchecked(e);\r\n}<\/pre>\n<p>And surprisingly this works! And even better, no rethrow-garbage, and also the throw location is right!<\/p>\n<pre class=\"csharpcode\">Exception in thread \"main\" ch.gamlor.test.OperationFailedException: Could not find appropriate example ;)\r\n    at ch.gamlor.test.ExceptionBlogPost.legacyMethodWithCheckedExceptions(ExceptionBlogPost.java:32)\r\n    at ch.gamlor.test.ExceptionBlogPost.methodWithoutCheckedException(ExceptionBlogPost.java:25)\r\n    at ch.gamlor.test.ExceptionBlogPost.openSimulation(ExceptionBlogPost.java:20)\r\n    at ch.gamlor.test.ExceptionBlogPost.demostrateStackTrace(ExceptionBlogPost.java:15)\r\n    at ch.gamlor.test.ExceptionBlogPost.main(ExceptionBlogPost.java:11)<\/pre>\n<p>\u00a0<\/p>\n<h3>Fine Tuning The Hack<\/h3>\n<p>Now we\u2019re facing the next problem. Supposed we\u2019ve a method which returns a value and we use out little hack. Then we\u2019ve a problem. Since the compiler doesn\u2019t see the \u2018exception\u2019, it requires you to return something or throw something. Well that\u2019s easy to fix. Change the signature from void to RuntimeException, so that you can throw it. But the implementation never actually returns, but throws the suppress checked exception.<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">public<\/span> final <span class=\"kwrd\">class<\/span> UncheckedThrow {\r\n    <span class=\"kwrd\">private<\/span> UncheckedThrow(){}\r\n\r\n    <span class=\"rem\">\/\/ Now this returns an exception, so that you can satisfy the compiler by throwing it.<\/span>\r\n    <span class=\"rem\">\/\/ But in reality we throw the given exception!<\/span>\r\n    <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">static<\/span> RuntimeException throwUnchecked(final Exception ex){\r\n        <span class=\"rem\">\/\/ Now we use the 'generic' method. Normally the type T is inferred<\/span>\r\n        <span class=\"rem\">\/\/ from the parameters. However you can specify the type also explicit!<\/span>\r\n        <span class=\"rem\">\/\/ Now we du just that! We use the RuntimeException as type!<\/span>\r\n        <span class=\"rem\">\/\/ That means the throwsUnchecked throws an unchecked exception!<\/span>\r\n        <span class=\"rem\">\/\/ Since the types are erased, no type-information is there to prevent this!<\/span>\r\n        UncheckedThrow.&lt;RuntimeException&gt;throwsUnchecked(ex);\r\n\r\n        <span class=\"rem\">\/\/ This is here is only to satisfy the compiler. It's actually unreachable code!<\/span>\r\n        <span class=\"kwrd\">throw<\/span> <span class=\"kwrd\">new<\/span> AssertionError(<span class=\"str\">\"This code should be unreachable. Something went terrible wrong here!\"<\/span>);\r\n    }\r\n\r\n    <span class=\"rem\">\/**<\/span>\r\n<span class=\"rem\">     * Remember, Generics are erased in Java. So this basically throws an Exception. The real<\/span>\r\n<span class=\"rem\">     * Type of T is lost during the compilation<\/span>\r\n<span class=\"rem\">     *\/<\/span>\r\n    <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">static<\/span> &lt;T extends Exception&gt; <span class=\"kwrd\">void<\/span> throwsUnchecked(Exception toThrow) throws T{\r\n        <span class=\"rem\">\/\/ Since the type is erased, this cast actually does nothing!!!<\/span>\r\n        <span class=\"rem\">\/\/ we can throw any exception<\/span>\r\n        <span class=\"kwrd\">throw<\/span> (T) toThrow;\r\n    }\r\n}<\/pre>\n<p>Now you can use it anywhere!<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">private<\/span> <span class=\"kwrd\">int<\/span> methodWithoutCheckedException() {\r\n    <span class=\"kwrd\">try<\/span>{\r\n        <span class=\"kwrd\">return<\/span> legacyMethodWithCheckedExceptions();\r\n    } <span class=\"kwrd\">catch<\/span> (OperationFailedException e){\r\n        <span class=\"kwrd\">throw<\/span> UncheckedThrow.throwUnchecked(e);\r\n    }\r\n}<\/pre>\n<p>It\u2019s not only limited to rethrows, you can throw a checked exception anywhere. However I think that\u2019s a very bad idea!<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">private<\/span> String demoJustThrow(){\r\n    <span class=\"kwrd\">throw<\/span> UncheckedThrow.throwUnchecked(<span class=\"kwrd\">new<\/span> IOException(<span class=\"str\">\"See, I'm not declared\"<\/span>));\r\n}<\/pre>\n<h3>Conclusion<\/h3>\n<p>I\u2019ve demonstrated how to throw checked exception like unchecked ones. Yes, this is certainly a real evil hack. However I also think that avoiding unnecessary garbage in stack traces is a real benefit. So I\u2019ve started to use this for rethrowing checked exceptions in my projects.<\/p>\n<p>I\u2019ve also to mention that this could be a weakness in the javac-compiler. I haven\u2019t checked this against the language definition =).<\/p>\n<p>The source-file is here. Try it yourself: <a href=\"https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/2010\/02\/UncheckedThrow.java\">UncheckedThrow.java<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u00a0 Everyone who\u2019s programming Java knows checked exceptions. You only can throw a checked exception when you\u2019ve declare it. And you have to catch an checked exception, no matter whether&hellip; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":"","_links_to":"","_links_to_target":""},"categories":[15],"tags":[160,295],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/posts\/1020"}],"collection":[{"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/comments?post=1020"}],"version-history":[{"count":10,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/posts\/1020\/revisions"}],"predecessor-version":[{"id":3847,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/posts\/1020\/revisions\/3847"}],"wp:attachment":[{"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/media?parent=1020"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/categories?post=1020"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/tags?post=1020"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}