美文网首页
优雅的try...catch

优雅的try...catch

作者: Crud仔 | 来源:发表于2020-12-30 22:22 被阅读0次

1.原有写法

        try {
            String str = null;
            System.out.println(str.length());
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

2.使用vavr

引入依赖

        <!-- https://mvnrepository.com/artifact/io.vavr/vavr -->
        <dependency>
            <groupId>io.vavr</groupId>
            <artifactId>vavr</artifactId>
            <version>1.0.0-alpha-3</version>
        </dependency>

编写测试

        // 它支持非常多的方法,可以完成大多数后续的业务处理
        Try.run(() -> {
            String str = null;
            System.out.println(str.length());
        }).onFailure(e -> e.printStackTrace());

总结

使用此写法可以将代码更加优雅.

相关文章

网友评论

      本文标题:优雅的try...catch

      本文链接:https://www.haomeiwen.com/subject/rpdkoktx.html