All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.dongliu.commons.Exceptions Maven / Gradle / Ivy

There is a newer version: 6.7.0
Show newest version
package net.dongliu.commons;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UncheckedIOException;

/**
 * Utils for exception
 *
 * @author Liu Dong {@literal }
 */
public class Exceptions {

    /**
     * Throw a exception with no need to declare throw clause in method signature
     */
    public static RuntimeException sneakyThrow(Throwable throwable) {
        Exceptions.unCheck(throwable);
        return null;
    }

    @SuppressWarnings("unchecked")
    private static  void unCheck(Throwable throwable) throws T {
        throw (T) throwable;
    }

    /**
     * Write exception stack trace to String
     */
    public static String writeToString(Throwable t) {
        try (StringWriter sw = new StringWriter();
             PrintWriter pw = new PrintWriter(sw)) {
            t.printStackTrace(pw);
            return sw.toString();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy