文章目录
《Lombok 实战 —— @SneakyThrows & @Synchronized》
@SneakyThrows
To boldly throw checked exceptions where no one has thrown them before!
1.1 @SneakyThrows 实战使用
@SneakyThrows
可用于偷偷抛出checked exception
,而无需在方法上的throws子句中声明需要抛出的异常。
由lombok
生成的代码,不会忽略,不会包装,不会替换或以其他方式修改抛出的checked exception
,而是将 checked exception
看做unchecked exception
,不处理,直接扔掉。
那么
lombok
是如何工作的呢?
在JVM(类文件)级别上,无论方法throw
什么异常,lombok
都可以抛出所有异常(无论是否是检查时异常),如下面一个简单的示例:
public class SneakyThrowsTest {
public static void main(String[] args) {
throwException();
}
@SneakyThrows
public static void throwException() {
String str = null;
String[] split = str.split(",");
System.out.println(split);
}
}
// 编译后:
public class SneakyThrowsTest {
public SneakyThrowsTest() {
}
public static void main(String[] args) {
throwException();
}
public static void throwException() {
try {
String str = null;
String[] split = ((String)str).split(",");
System.out.println(split);
}