| 知乎专栏 |
public static void exceptionTest() {
File file = new File("/tmp/test.txt");
try {
FileReader fileReader = new FileReader(file);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void exceptionTest() throws Exception {
File file = new File("/tmp/test.txt");
FileReader fileReader = new FileReader(file);
}
使用 @SneakyThrows 注解,替代写法
@SneakyThrows
public static void exceptionTest(String pathname) {
File file = new File(pathname);
FileReader fileReader = new FileReader(file);
}
public static void exceptionTest() {
File file = new File("/tmp/test.txt");
try {
FileReader fileReader = new FileReader(file);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
public static void exceptionTest() throws FileNotFoundException {
File file = new File("/tmp/test.txt");
FileReader fileReader = new FileReader(file);
}
使用 @SneakyThrows 注解,替代写法
@SneakyThrows(FileNotFoundException.class)
public static void exceptionTest(File file) {
FileReader fileReader = new FileReader(file);
}
package cn.netkiller.test;
import lombok.SneakyThrows;
public class Test {
@SneakyThrows
public static void throwExceptionTest(String message) {
throw new IllegalStateException(message);
}
public static void main(String[] args) {
try {
throwExceptionTest("Test");
} catch (Exception e) {
System.out.println(e);
}
}
}