Java Lombok | throwsの自動指定 - @SneakyThrows
@SneakyThrows
メソッドに@SneakyThrowsアノテーションを宣言すると、内部でチェック例外が発生してもthrowsを付けなくてよい。
- sneakyは「こっそり」という意味である。
package com.devkuma.tutorial.lombok;
import lombok.SneakyThrows;
public class SneakyThrowsTutorial {
public static void main(String[] args) {
method();
}
@SneakyThrows
private static void method() {
throw new Exception("test");
}
}
実行結果:
Exception in thread "main" java.lang.Exception: test
at com.devkuma.tutorial.lombok.SneakyThrowsTutorial.method(SneakyThrowsTutorial.java:12)
at com.devkuma.tutorial.lombok.SneakyThrowsTutorial.main(SneakyThrowsTutorial.java:7)
指定した例外だけを無視する
package com.devkuma.tutorial.lombok;
import lombok.SneakyThrows;
import java.io.IOException;
public class SneakyThrowsTutorial2 {
public static void main(String[] args) {
method();
}
@SneakyThrows(IOException.class)
private static void method() {
try {
throw new Exception("test");
} catch (Exception e) {
// catch가 없으면 에러가 발생한다.
}
throw new IOException();
}
}
実行結果:
Exception in thread "main" java.io.IOException
at com.devkuma.tutorial.lombok.SneakyThrowsTutorial2.method(SneakyThrowsTutorial2.java:20)
at com.devkuma.tutorial.lombok.SneakyThrowsTutorial2.main(SneakyThrowsTutorial2.java:9)
valueとして例外Classオブジェクトを渡すことで、指定した例外だけを無視できるようになる。