A little secret about throw exception in Java

A little secret about throw exception in Java

brief introduction

In the previous article, we mentioned that to handle exceptions in stream, you need to convert checked exception to unchecked exception.

We did this:

    static <T> Consumer<T> consumerWrapper(
            ThrowingConsumer<T,Exception> throwingConsumer) {

        return i -> {
            try {
                throwingConsumer.accept(i);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        };
    }

The exception is caught and encapsulated as a runtimeException.

Encapsulating runtimeException always feels like there is a little problem, so is there a better way?

Throw tips

We should all know the type inference of Java. If it is in this form, t will be considered as runtimeException!

Let's look at the following example:

public class RethrowException {

    public static <T extends Exception,R> R throwException(Exception t) throws T {
        throw (T) t; // just throw it,convert checked exception to unchecked exception
    }

}

In the above class, we define a throwexception method, which receives an exception parameter and converts it to t, where t is an unchecked exception.

Next, let's look at the specific usage:

@Slf4j
public class RethrowUsage {

    public static void main(String[] args) {
        try {
            throwIOException();
        } catch (IOException e) {
           log.error(e.getMessage(),e);
            RethrowException.throwException(e);
        }
    }

    static void throwIOException() throws IOException{
        throw new IOException("io exception");
    }
}

In the above example, we converted an IOException into an unchecked exception.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>