Lombok @SneakyThrows用法如下。
Java處理應捕捉的例外(checked exception)的方式有兩種,一為在方法後用throws向外拋出, 一為使用try ... catch區塊捕捉例外並處理。
throws向外拋出
void write(byte[] data, String path) throws IOException {
File file = new File(path);
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(data); // 寫出檔案
}
}
try ... catch例外處理
void write(byte[] data, String path) {
File file = new File(path);
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(data); // 寫出檔案
} catch (IOException e) {
// 例外處理
}
}
而@SneakyThrows可以把方法中應捕捉的例外偷偷包裝成Throwable拋出,因此原本應用throws拋出或用try ... catch處理的例外就變得不用在這處理直接外拋到Thread的UncaughtExceptionHandler處理。
使用@SneakyThrows
void writeFile(String str, String path) {
byte[] data = str.getBytes();
write(data, path);
}
@SneakyThrows(IOException.class)
void write(byte[] data, String path) {
File file = new File(path);
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(data);
}
}
Lombok其實做了以下修改。
void write(byte[] data, String path) {
File file = new File(path);
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(data);
} catch (IOException e) {
throw Lombok.sneakyThrow(e); // 包裝成Throwable
}
}
參考github。
沒有留言:
張貼留言