SneakyThrow is a Java library to ignore checked exceptions

Overview

SneakyThrow

Build Status Coverage Status MIT Licence Maven Central Javadocs

SneakyThrow is a Java library to ignore checked exceptions. You can integrate it using maven:

<dependency>
  <groupId>com.rainerhahnekamp</groupId>
  <artifactId>sneakythrow</artifactId>
  <version>1.2.0</version>
</dependency>

SneakyThrow Usage GIF

Usage

Without SneakyThrow:

URL url;
try {
  url = new URL("https://www.hahnekamp.com");
} catch (MalformedURLException mue) {
  throw new RuntimeException(mue);
}

With SneakyThrow:

URL url = sneak(() -> new URL("https://www.hahnekamp.com"));

Usage with Java 8 Streams

private URL createURL(String url) throws MalformedURLException {
  return new URL(url);
}

The function above used within a Stream without SneakyThrow:

Stream
  .of("https://www.hahnekamp.com", "https://www.austria.info")
  .map(url -> {
    try {
      return this.createURL(url);
    } catch (MalformedURLException mue) {
      throw new RuntimeException(mue);
    }
  })  
  .collect(Collectors.toList());

Again with SneakyThrow:

Stream
  .of("https://www.hahnekamp.com", "https://www.austria.info")
  .map(sneaked(this::createURL))
  .collect(Collectors.toList());

The static method sneaked wraps each function, that has the same signature as a functional interface (java.util.functional).

Please note the difference between sneak and sneaked.

How it works

This project is heavily influenced by ThrowingFunction.

In SneakyThrow, each functional interface, defined in java.util.function, has an equivalent one with the same signature. The only difference is, that these "Sneaky Functional Interfaces" throw exceptions. This gives us the possibility to write lambdas or similar code that also throws exceptions.

Both sneak and sneaked wrap the passed "Sneaky Functional Interfaces" into a try/catch clause and return the equivalent java.util.function interface. In the case of sneak, execution and the return of the result is done immediately.

You might also like...

Some anti afk bot which prevents you from getting punished for going afk in games. Way of stopping the bot is slightly flawed but we'll ignore that.

Some anti afk bot which prevents you from getting punished for going afk in games. Way of stopping the bot is slightly flawed but we'll ignore that.

AntiAFK Some anti afk bot which prevents you from getting punished for going afk in games. Gui mode coming soon... Installation Install Java 17. Downl

Jan 13, 2022

Fabric mod to (maybe) ignore global bans while still using the auth server

=== SECURITY WARNING === DO NOT USE THIS MOD IF YOU DO NOT 100% TRUST THE SERVER NOT TO STEAL YOUR ACCOUNT. This mod is not secure because servers wil

Dec 20, 2022

Test case to check if the Log4Shell/CVE-2021-44228 hotfix will raise any unexpected exceptions

Log4Shell Hotfix Side Effect Test Case I wanted to know if any ClassNotFoundException or similar unexpected exception is raised when one applies the C

Nov 9, 2022

Duck Library is a library for developers who don't want to spend their time to write same library consistently.

Duck Library is a library for developers who don't want to spend their time to write same library consistently.

Duck Library is a library for developers who don't want to spend their time to write same library consistently. It has almost every useful feature to

Jul 28, 2022

This is an automated library software built in Java Netbeans to reduce manual efforts of the librarian, students to ensure smooth functioning of library by involving RFIDs.

This is an automated library software built in Java Netbeans to reduce manual efforts of the librarian, students to ensure smooth functioning of library by involving RFIDs.

Advanced-Library-Automation-System This is an advanced automated library software built in Java Netbeans to reduce manual efforts of the librarian, st

Dec 6, 2022

Tinker is a hot-fix solution library for Android, it supports dex, library and resources update without reinstall apk.

Tinker is a hot-fix solution library for Android, it supports dex, library and resources update without reinstall apk.

Tinker Tinker is a hot-fix solution library for Android, it supports dex, library and resources update without reinstalling apk. Getting started Add t

Dec 30, 2022

Diff Utils library is an OpenSource library for performing the comparison / diff operations between texts or some kind of data: computing diffs

Diff Utils library is an OpenSource library for performing the comparison / diff operations between texts or some kind of data: computing diffs, applying patches, generating unified diffs or parsing them, generating diff output for easy future displaying (like side-by-side view) and so on.

Jan 5, 2023

Microserver is a Java 8 native, zero configuration, standards based, battle hardened library to run Java Rest Microservices via a standard Java main class. Supporting pure Microservice or Micro-monolith styles.

Microserver is a Java 8 native, zero configuration, standards based, battle hardened library to run Java Rest Microservices via a standard Java main class. Supporting pure Microservice or Micro-monolith styles.

Microserver A convenient modular engine for Microservices. Microserver plugins offer seamless integration with Spring (core), Jersey, Guava, Tomcat, G

Dec 19, 2022

Microserver is a Java 8 native, zero configuration, standards based, battle hardened library to run Java Rest Microservices via a standard Java main class. Supporting pure Microservice or Micro-monolith styles.

Microserver is a Java 8 native, zero configuration, standards based, battle hardened library to run Java Rest Microservices via a standard Java main class. Supporting pure Microservice or Micro-monolith styles.

Microserver is a Java 8 native, zero configuration, standards based, battle hardened library to run Java Rest Microservices via a standard Java main class. Supporting pure Microservice or Micro-monolith styles.

Dec 19, 2022

Spoon is a metaprogramming library to analyze and transform Java source code (up to Java 15). :spoon: is made with :heart:, :beers: and :sparkles:. It parses source files to build a well-designed AST with powerful analysis and transformation API.

Spoon Spoon is an open-source library to analyze, rewrite, transform, transpile Java source code. It parses source files to build a well-designed AST

Dec 29, 2022

A Java serialization/deserialization library to convert Java Objects into JSON and back

Gson Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to a

Jan 8, 2023

Java Statistical Analysis Tool, a Java library for Machine Learning

Java Statistical Analysis Tool JSAT is a library for quickly getting started with Machine Learning problems. It is developed in my free time, and made

Dec 20, 2022

A modular and portable open source XMPP client library written in Java for Android and Java (SE) VMs

Smack About Smack is an open source, highly modular, easy to use, XMPP client library written in Java for Java SE compatible JVMs and Android. A pure

Dec 28, 2022

A Java library that implements a ByteChannel interface over SSLEngine, enabling easy-to-use (socket-like) TLS for Java applications.

TLS Channel TLS Channel is a library that implements a ByteChannel interface over a TLS (Transport Layer Security) connection. It delegates all crypto

Dec 31, 2022

A Java architecture test library, to specify and assert architecture rules in plain Java

A Java architecture test library, to specify and assert architecture rules in plain Java

ArchUnit is a free, simple and extensible library for checking the architecture of your Java code. That is, ArchUnit can check dependencies between pa

Jan 2, 2023

icecream-java is a Java port of the icecream library for Python.

icecream-java is a Java port of the icecream library for Python.

Apr 7, 2022

JPassport works like Java Native Access (JNA) but uses the Foreign Linker API instead of JNI. Similar to JNA, you declare a Java interface that is bound to the external C library using method names.

JPassport works like Java Native Access (JNA) but uses the Foreign Linker API instead of JNI. Similar to JNA, you declare a Java interface that is bound to the external C library using method names.

JPassport works like Java Native Access (JNA) but uses the Foreign Linker API instead of JNI. Similar to JNA, you declare a Java interface t

Dec 30, 2022

Trust-java - Test Results Verification library for Java

TRUST - Test Results Verification library for Java The TRUST's primary goal is to provide the simple way of different test results verification. Gener

Nov 19, 2017
Comments
  • Do not wrap exceptions

    Do not wrap exceptions

    Hi,

    thx for your library however I would appreciate if you wouldn't wrap exceptions. You can throw checked exceptions with following usage of generics.

    public class ExceptionUtils {
        
        /**
         * Throws {@code t} as a unchecked exception.
         */
        @SuppressWarnings("unchecked")
        public static <T extends Throwable> void throwUnchecked(Throwable t) throws T {
            throw (T) t;
        }
    
    
        public static void main(String[] args) {
    
          Exception e = new Exception("Boom!");
    
          throwUnchecked(e);
        }
        
    }
    
    opened by qoomon 3
  • Avoid rethrowing exception in functional wrappers

    Avoid rethrowing exception in functional wrappers

    Currently sneaked functions rethrow exceptions which incurs some performance penalty. It's possible to avoid that with slightly changed signatures of SneakyFunction, etc. Example:

    @FunctionalInterface
    public interface SneakyFunction<T, R, E extends Exception> {
        R apply(T t) throws E;
    }
    
    public static <T, R, E extends Exception> Function<T, R> sneaked(SneakyFunction<T, R, E> function) {
        return t -> {
            @SuppressWarnings("unchecked") SneakyFunction<T, R, RuntimeException> f1 = (SneakyFunction<T, R, RuntimeException>) function;
            return f1.apply(t);
        };
    }
    
    opened by vbezhenar 2
Releases(v1.2.0)
Owner
Rainer Hahnekamp
Rainer Hahnekamp is a software engineer and is constantly searching for tools and techniques to improve code quality. He is also trainer at AngularArchitects.io
Rainer Hahnekamp
A library that simplifies error handling for Functional Programming in Java

Faux Pas: Error handling in Functional Programming Faux pas noun, /fəʊ pɑː/: blunder; misstep, false step Faux Pas is a library that simplifies error

Zalando SE 114 Dec 5, 2022
Java 1-15 Parser and Abstract Syntax Tree for Java, including preview features to Java 13

JavaParser This project contains a set of libraries implementing a Java 1.0 - Java 14 Parser with advanced analysis functionalities. This includes pre

JavaParser 4.5k Jan 5, 2023
Dynamic Code Evolution VM for Java 7/8

NEWS: Dcevm-11 on Trava OpenJDK There is a new distribution channel for DCEVM-11 binaries on - TravaOpenjdk! DCEVM This project is a fork of original

null 1.6k Dec 28, 2022
Java unlimited redefinition of classes at runtime.

Hotswap Agent This is an overview page, please visit hotswapagent.org for more information. Overview Java unlimited runtime class and resource redefin

null 1.9k Dec 30, 2022
simple tail call optimization and stack safety for Java

com.github.kag0.tail simple tail call optimization for Java enables infinitely deep tail recursive calls without throwing a StackOverflowError no tran

Nathaniel Fischer 18 Dec 7, 2022
Project on End to End CI/CD pipeline for java based application using Git,Github,Jenkins,Maven,Sonarqube,Nexus,Slack,Docker and Kuberenets with ECR as private docker registry and Zero Downtime Deployment

Project on End to End CI/CD pipeline for java based application using Git,Github,Jenkins,Maven,Sonarqube,Nexus,Slack,Docker and Kuberenets with ECR as private docker registry and Zero Downtime Deployment.

NITHIN JOHN GEORGE 10 Nov 22, 2022
Java utilities to throw checked exceptions in a "sneaky" way.

Sneaky Java Java utilities to throw checked exceptions in a "sneaky" way. If you're tired of checked exceptions in lambdas, then this library is made

Semyon Kirekov 24 Dec 3, 2022
Java library for handling exceptions in concise, unified, and architecturally clean way.

NoException NoException is a Java library for handling exceptions in concise, unified, and architecturally clean way. System.out.println(Exceptions.lo

Robert Važan 79 Nov 17, 2022
Win32 and DirectX mappings for java using Project Panama. Ignore the C# tag, it's just reference code used for decompilation

JWin32 A Project Panama-based mapping + wrapper generator for win32 headers. IMPORTANT As of 0.5.0, no prebuilt jars will be provided. You must genera

FalsePattern 9 Nov 27, 2022