程序员

如何处理Java 中的Checked Exception

2018-12-22  本文已影响8人  brackenbo

想必很多人对JAVA中的Exception不会陌生,但是我们也会碰到诸多的Checked Exception。而我们又不想一层层去捕获,那么就需要想办法来忽略这些Checked Exception。

那么何为Checked Exception, 何为Unchecked Exception。


所示

正如上图中所示:

如果在代码中处处来处理Checked Exception,那么代码就会变成冗长并且可读性变差,所以在某些情况下需要对其进行处理,变成Unchecked Exception。

1. try catch

最简单的方案之一就是使用try catch然后在捕获到checked exception之后抛出Unchecked Exception。

例如:

public DbConnection getDbConnection(String username, String password) {

    try {
        return new DbProvider().getConnect(username, password);
    } catch (IOException e) {
        throw new RuntimeException();
    }
  }

这样的处理逻辑到处都会用到,代码也会显得冗长,降低了可读性。

2. 一个通用的Wrapper

可以尝试着写一个通用的Wrapper,统一处理类似的Checked Exception。

public class RuntimeExceptionWrapper {

    public static <T> T wrap(RuntimeExceptionWrappable<T> wrappable) {
        try {
            return wrappable.execute();
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }
}
    RuntimeExceptionWrappable<DbConnection> wrappable = new RuntimeExceptionWrappable<DbConnection>() {

        @Override
        public DbConnection execute() throws IOException {
            return new DbProvider().getConnect(username, password);
        }
    };

    return RuntimeExceptionWrapper.wrap(wrappable);

到这里就可以看到,Wrapper被抽象到独立的类中了。

3. Stream中的Exception

自从JAVA8依赖,流处理在代码中已经变得越来越常见,这样就不可避免的会有Exception出现在Stream流处理中。

public class UrlHandler {

    public List<URL> getURLs() {
        return Stream.of("http://www.baidu.com", "https://www.google.com")
            .map(this:createURL)
            .collect(Collectors.toList());
    }

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

上述代码是编译不通过的,原因是createURL抛出了Checked Exception。只有对stream流处理进行修改,接收Exception代码才能编译:

public List<URL> getURLs() {
    return Stream.of("http://www.baidu.com", "https://www.google.com")
            .map(url -> {
                try {
                    return this.createURL(url);
                } catch (MalformedURLException e) {
                    throw new RuntimeException();
                }
            })
            .collect(Collectors.toList());
}

这段代码虽然能够工作,但是依然显得不是很优雅。还是跟前一部分一样,我们抽取出来一个通用的Wrapper。

@FunctionalInterface
public interface RuntimeWrappableFunction<T, R> {
    R apply(T t) throws Exception;
}
public class RuntimeWrappableFunctionMapper {
    public static <T, R> Function<T, R> wrap(RuntimeWrappableFunction<T, R> wrappableFunction) {
        return t -> {
            try {
                return wrappableFunction.apply(t);
            } catch (Exception e) {
                throw new RuntimeException();
            }
        };
    }
}
public class UrlHandler {

    public List<URL> getURLs() {
        return Stream.of("http://www.baidu.com", "https://www.google.com")
            .map(RuntimeWrappableFunctionMapper.wrap(this::createURL))
            .collect(Collectors.toList());
}

    private URL createURL(String url) throws MalformedURLException {
        return new URL(url);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读