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());
总结
使用此写法可以将代码更加优雅.
网友评论