<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Sneakythrow - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Sneakythrow - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 11 Jun 2026 11:19:01 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/sneakythrow/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Why you should ignore exceptions in Java and how to do it correctly ]]>
                </title>
                <description>
                    <![CDATA[ By Rainer Hahnekamp In this article, I will show how to ignore checked exceptions in Java. I will start by describing the rationale behind it and the common pattern to resolve this issue. Then I will present some libraries for that purpose. Checked a... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/why-you-should-ignore-exceptions-in-java-and-how-to-do-it-correctly-8e95e5775e58/</link>
                <guid isPermaLink="false">66c3675d0cede4e9b1329d68</guid>
                
                    <category>
                        <![CDATA[ Sneakythrow ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 03 May 2018 23:48:14 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*zL-r1LMISdwKu2y47rsROQ.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Rainer Hahnekamp</p>
<p>In this article, I will show how to ignore checked exceptions in Java. I will start by describing the rationale behind it and the common pattern to resolve this issue. Then I will present some libraries for that purpose.</p>
<h3 id="heading-checked-and-unchecked-exceptions">Checked and Unchecked Exceptions</h3>
<p>In Java, a method can force its caller to deal with the occurrence of potential exceptions. The caller can use the try/catch clause, where the try contains the actual code and catch contains the code to execute when the exception occurs.</p>
<p>Alternatively, the caller can pass on that burden to its <strong>parent caller</strong>. This can go upwards until the main method is reached. If the main method also passes on the exception, the application will crash when an exception happens.</p>
<p>In the case of an exception, there are many scenarios where the application cannot continue to run and needs to stop. There are no alternative paths. Unfortunately, that means Java forces us to write code for a situation where the application shouldn’t run anymore. Quite useless!</p>
<p>An option is to minimise that boilerplate code. We can wrap the exception into a <strong>RuntimeException</strong>, which is an unchecked exception. This has the effect that, even though the application still crashes, we don’t have to provide any handling code.</p>
<p>By no means do we log the exception and let the application continue like nothing has happened. It is possible, but is similar to opening Pandora’s Box.</p>
<p>We call these exceptions, for which we have to write extra code, <strong>checked exceptions.</strong> The others of the <strong>RuntimeException</strong> type we call <strong>unchecked exceptions</strong>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/Dgx2RgjqtCmRsIuyoTzcBVKr7BwUO4EnT1KK" alt="Image" width="768" height="313" loading="lazy">
<em>Checked and Unchecked Exceptions</em></p>
<h3 id="heading-why-checked-exceptions-at-all">Why Checked Exceptions at all?</h3>
<p>We can find lots of checked exceptions in third-party libraries, and even in the Java Class Library itself. The reason is pretty straightforward. A library vendor cannot predict in which context the developer will use their code.</p>
<p>Logically, they don’t know if our application has alternative paths. So they leave the decision to us. Their responsibility is to “label” methods that can potentially throw exceptions. Those labels give us the chance to implement counter-actions.</p>
<p>A good example is the connection to a database. The library vendor marks the connection retrieval method with an exception. If we use the database as a cache, we can send our queries directly to our primary database. This is the alternative path.</p>
<p>If our database is not the cache, there is no way the application can continue to run. And it’s OK if the application crashes:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/LJlE2Wwpgm0D17OoIMoEUTEgyaGbeKRCwuaA" alt="Image" width="423" height="600" loading="lazy">
_<a target="_blank" href="https://thepracticaldev.s3.amazonaws.com/i/600zwkafhw4pjiniwzv5.jpg">https://imgflip.com/i/26h3xi](https://imgflip.com/i/26h3xi</a>" rel="noopener" target="<em>blank" title=")</em></p>
<h3 id="heading-a-lost-database">A lost database</h3>
<p>Let’s put our theoretical example to real code:</p>
<pre><code>public DbConnection getDbConnection(<span class="hljs-built_in">String</span> username, <span class="hljs-built_in">String</span> password) {  <span class="hljs-keyword">try</span> {    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> DbProvider().getConnection(username, password);  } <span class="hljs-keyword">catch</span> (DbConnectionException dce) {    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(dce);  }}
</code></pre><p>The database is not used as a cache. In the event of a lost connection, we need to stop the application at once.</p>
<p>As described above, we wrap the <strong>DbConnectionException</strong> into a <strong>RuntimeException</strong>.</p>
<p>The required code is relatively verbose and always the same. This creates lots of duplication and decreases the readability.</p>
<h3 id="heading-the-runtimeexception-wrapper">The RuntimeException Wrapper</h3>
<p>We can write a function to simplify this. It should wrap a <strong>RuntimeException</strong> over some code and return the value. We cannot simply pass code in Java. The function must be part of a class or interface. Something like this:</p>
<pre><code>public interface RuntimeExceptionWrappable&lt;T&gt; {  T execute() throws Exception;} public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RuntimeExceptionWrapper</span> </span>{  public <span class="hljs-keyword">static</span> &lt;T&gt; T wrap(RuntimeExceptionWrappable&lt;T&gt; runtimeExceptionWrappable) {    <span class="hljs-keyword">try</span> {      <span class="hljs-keyword">return</span> runtimeExceptionWrappable.execute();    } <span class="hljs-keyword">catch</span> (Exception exception) {      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(exception);    }  }} public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DbConnectionRetrieverJava7</span> </span>{  public DbConnection getDbConnection(final <span class="hljs-built_in">String</span> username, final <span class="hljs-built_in">String</span> password) {    RuntimeExceptionWrappable&lt;DbConnection&gt; wrappable = <span class="hljs-keyword">new</span> RuntimeExceptionWrappable&lt;DbConnection&gt;() {      public DbConnection execute() throws Exception {        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> DbProvider().getConnection(username, password);      }    };    <span class="hljs-keyword">return</span> RuntimeExceptionWrapper.wrap(wrappable);  }}
</code></pre><p>The <strong>RuntimeException</strong> wrapping has been extracted into its own class. In terms of software design, this might be the more elegant solution. Still, given the amount of code, we can hardly say the situation got better.</p>
<p>With Java 8 lambdas, things got easier. If we have an interface with one method only, then we just write the specific code of that method. The compiler does the rest for us. The unnecessary or “syntactic sugar code” to create a specific or anonymous class is not required any more. That’s the basic use case for Lambdas.</p>
<p>In Java 8, our example above looks like:</p>
<pre><code>@FunctionalInterfacepublic interface RuntimeExceptionWrappable&lt;T&gt; {  T execute() throws Exception;} public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DbConnectionRetrieverJava8</span> </span>{  public DbConnection getDbConnection(<span class="hljs-built_in">String</span> username, <span class="hljs-built_in">String</span> password) {    <span class="hljs-keyword">return</span> RuntimeExceptionWrapper.wrap(() -&gt;      <span class="hljs-keyword">new</span> DbProvider().getConnection(username, password));  }}
</code></pre><p>The difference is quite clear: the code is more concise.</p>
<h3 id="heading-exceptions-in-streams-amp-co">Exceptions in Streams &amp; Co.</h3>
<p><code>RuntimeExceptionWrappable</code> is a very generic interface. It is just a function that returns a value. Use cases for that function, or its variations, appear all over. For our convenience, Java’s Class Library has a set of such common Interfaces built-in. They are in the package <code>java.util.function</code> and are better known as the “Functional Interfaces.” Our <code>RuntimeExceptionWrappable</code> is similar to <code>java.util.function.Supplier&lt;</code>;T&gt;.</p>
<p>These interfaces form the prerequisite of the powerful Stream, Optional, and other features which are also part of Java 8. In particular, Stream comes with a lot of different methods for processing collections. Many of these methods have a “Functional Interface” as parameter.</p>
<p>Let’s quickly switch the use case. We have a list of URL strings that we want to map into a list of objects of type java.net.URL.</p>
<p>The following code <strong>does not compile</strong>:</p>
<pre><code>public List&lt;URL&gt; getURLs() {  <span class="hljs-keyword">return</span> Stream    .of(“https:<span class="hljs-comment">//www.hahnekamp.com", “https://www.austria.info")    .map(this::createURL)    .collect(Collectors.toList());} private URL createURL(String url) throws MalformedURLException {  return new URL(url);}</span>
</code></pre><p>There is a big problem when it comes to exceptions. The Interfaces defined in <code>java.util.function</code> don’t throw exceptions. That’s why our method <strong>createURL</strong> doesn’t have the same signature as <code>java.util.function.Function</code>, which is the parameter of the map method.</p>
<p>What we can do is to write the try/catch block inside the lambda:</p>
<pre><code>public List&lt;URL&gt; getURLs() {  <span class="hljs-keyword">return</span> Stream    .of(“https:<span class="hljs-comment">//www.hahnekamp.com", “https://www.austria.info")    .map(url -&gt; {      try {        return this.createURL(url);      } catch (MalformedURLException e) {        throw new RuntimeException(e);      }    })    .collect(Collectors.toList());}</span>
</code></pre><p>This compiles, but doesn’t look nice either. We can now take a step further and write a wrapper function along a new interface similar to `RuntimeExceptionWrappable``:</p>
<pre><code>@FunctionalInterfacepublic interface RuntimeWrappableFunction&lt;T, R&gt; {  R apply(T t) throws Exception;} public <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RuntimeWrappableFunctionMapper</span> </span>{  public <span class="hljs-keyword">static</span> &lt;T, R&gt; <span class="hljs-built_in">Function</span>&lt;T, R&gt; wrap(    RuntimeWrappableFunction&lt;T, R&gt; wrappable) {      <span class="hljs-keyword">return</span> t -&gt; {        <span class="hljs-keyword">try</span> {          <span class="hljs-keyword">return</span> wrappable.apply(t);        } <span class="hljs-keyword">catch</span>(Exception exception) {          <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(exception);        }      };    }}
</code></pre><p>And apply it to our Stream example:</p>
<pre><code>public List&lt;URL&gt; getURLs() {  <span class="hljs-keyword">return</span> Stream    .of(“https:<span class="hljs-comment">//www.hahnekamp.com”, “https://www.austria.info”)    .map(RuntimeWrappableFunctionMapper.wrap(this::createURL))    .collect(Collectors.toList());} private URL createURL(String url) throws MalformedURLException {  return new URL(url);}</span>
</code></pre><p>Great! Now we have a solution, where we can:</p>
<ul>
<li>run code without catching checked exceptions, and</li>
<li>use exception-throwing lambdas in Stream, Optional, and so on.</li>
</ul>
<h3 id="heading-sneakythrow-to-the-rescue">SneakyThrow to the rescue</h3>
<p>The SneakyThrow library lets you skip copying and pasting the code snippets from above. Full disclosure: I am the author.</p>
<p>SneakyThrow comes with two static methods. One runs code without catching checked exceptions. The other method wraps an exception-throwing lambda into one of the Functional Interfaces:</p>
<pre><code><span class="hljs-comment">//SneakyThrow returning a resultpublic DbConnection getDbConnection(String username, String password) {  return sneak(() -&gt; new DbProvider().getConnection(username, password));} //SneakyThrow wrapping a functionpublic List&lt;URL&gt; getURLs() {  return Stream    .of(“https://www.hahnekamp.com", “https://www.austria.info")    .map(sneaked(this::createURL))    .collect(Collectors.toList());}</span>
</code></pre><h3 id="heading-alternative-libraries">Alternative Libraries</h3>
<h4 id="heading-throwingfunction">ThrowingFunction</h4>
<pre><code><span class="hljs-comment">//ThrowingFunction returning a resultpublic DbConnection getDbConnection(String username, String password) {  return unchecked(() -&gt;     new DbProvider().getConnection(username, password)).get();} //ThrowingFunction returning a functionpublic List&lt;URL&gt; getURLs() {  return Stream    .of(“https://www.hahnekamp.com", “https://www.austria.info")    .map(unchecked(this::createURL))    .collect(Collectors.toList());}</span>
</code></pre><p>In contrast to SneakyThrow, ThrowingFunction can’t execute code directly. Instead, we have to wrap it into a Supplier and call the Supplier afterwards. This approach can be more verbose than SneakyThrow.</p>
<p>If you have multiple unchecked Functional Interfaces in one class, then you have to write the full class name with each static method. This is because unchecked does not work with method overloading.</p>
<p>On the other hand, ThrowingFunction provides you with more features than SneakyThrow. You can define a specific exception you want to wrap. It is also possible that your function returns an Optional, otherwise known as “lifting.”</p>
<p>I designed SneakyThrow as an opinionated wrapper of ThrowingFunction.</p>
<h4 id="heading-vavr">Vavr</h4>
<p>Vavr, or “JavaSlang,” is another alternative. In contrast to SneakyThrow and ThrowingFunction, it provides a complete battery of useful features that enhance Java’s functionality.</p>
<p>For example, it comes with pattern matching, tuples, its own Stream and much more. If you haven’t heard of it, it is definitely worth a look. Prepare to invest some time in order to understand its full potential.</p>
<pre><code><span class="hljs-comment">//Vavr returning a resultpublic DbConnection getDbConnection(String username, String password) {  return Try.of(() -&gt;   new DbProvider().getConnection(username, password))    .get();} //Vavr returning a functionpublic List&lt;URL&gt; getURLs() {  return Stream    .of(“https://www.hahnekamp.com", “https://www.austria.info")    .map(url -&gt; Try.of(() -&gt; this.createURL(url)).get())    .collect(Collectors.toList());}</span>
</code></pre><h4 id="heading-project-lombok">Project Lombok</h4>
<p>Such a list of libraries is not complete without mentioning Lombok. Like Vavr, it offers much more functionality than just wrapping checked exceptions. It is a code generator for boilerplate code and creates full Java Beans, Builder objects, logger instances, and much more.</p>
<p>Lombok achieves its goals by bytecode manipulation. Therefore, we require an additional plugin in our IDE.</p>
<p>@SneakyThrows is Lombok’s annotation for manipulating a function with a checked exception into one that doesn’t. This approach doesn’t depend on the usage of lambdas, so you can use it for all cases. It is the least verbose library.</p>
<p>Please keep in mind that Lombok manipulates the bytecode which can cause problems with other tooling you might use.</p>
<pre><code><span class="hljs-comment">//Lombok returning a result@SneakyThrowspublic DbConnection getDbConnection(String username, String password) {  return new DbProvider().getConnection(username, password);} //Lombok returning a functionpublic List&lt;URL&gt; getURLs() {  return Stream    .of(“https://www.hahnekamp.com", “https://www.austria.info")    .map(this::createURL)    .collect(Collectors.toList());} @SneakyThrowsprivate URL createURL(String url) {  return new URL(url);}</span>
</code></pre><h4 id="heading-further-reading">Further Reading</h4>
<p>The code is available on <a target="_blank" href="https://github.com/rainerhahnekamp/ignore-exception">GitHub</a></p>
<ul>
<li><a target="_blank" href="https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html">https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html</a></li>
<li><a target="_blank" href="https://www.artima.com/intv/handcuffs.html">https://www.artima.com/intv/handcuffs.html</a></li>
<li><a target="_blank" href="http://www.informit.com/articles/article.aspx?p=2171751&amp;seqNum=3">http://www.informit.com/articles/article.aspx?p=2171751&amp;seqNum=3</a></li>
<li><a target="_blank" href="https://github.com/rainerhahnekamp/sneakythrow">https://github.com/rainerhahnekamp/sneakythrow</a></li>
<li><a target="_blank" href="https://projectlombok.org/features/SneakyThrows">https://projectlombok.org/features/SneakyThrows</a></li>
<li><a target="_blank" href="https://github.com/pivovarit/ThrowingFunction">https://github.com/pivovarit/ThrowingFunction</a></li>
<li><a target="_blank" href="https://github.com/vavr-io/vavr">https://github.com/vavr-io/vavr</a></li>
<li><a target="_blank" href="http://www.baeldung.com/java-lambda-exceptions">http://www.baeldung.com/java-lambda-exceptions</a></li>
</ul>
<p><em>Originally published at <a target="_blank" href="https://www.rainerhahnekamp.com/en/ignoring-exceptions-in-java/">www.rainerhahnekamp.com</a> on March 17, 2018.</em></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
