
Pada Java 8 terdapat Functional Interface yang dapat digunakan sebagai Lambda. Namun mayoritas Functional Interface tersebut by default tidak melakukan throws Exception. Ini cukup ribet kalau kita memanggil method yang throws checked exception pada scope Lambda pada umumnya. Contohnya kita ingin melakukan looping String yang berisi path sebuah text menggunakan lambda kemudian text tersebut dibaca dan di-print pada console seperti pada code berikut:
public class TextPrinter{
public void printText(String path)throws Exception{
try(FileInputStream fis = new FileInputStream(path)){
int intChar;
while((intChar = fis.read()) != -1){
System.out.print((char) intChar);
}
}
}
public void execute(List<String> paths) throws Exception{
paths.forEach((path) -> printText(path));
}
}
Code di atas akan compile error karena method foreach() menerima Functional Interface Consumer yang tidak melakukan throws checked exception, sedangkan method printText() yang dipanggil dalam lambda throws Exception. Mau gak mau code pada lambda harus ditambahkan try catch dulu di dalamnya. Contohnya seperti berikut:
public class TextPrinter{
public void printText(String path)throws Exception{
try(FileInputStream fis = new FileInputStream(path)){
int intChar;
while((intChar = fis.read()) != -1){
System.out.print((char) intChar);
}
}
}
public void execute(List<String> paths) throws Exception{
paths.forEach((path) -> {
try{
printText(path);
} catch(Exception e){
throw new RuntimeException(e.getMessage(), e);
}
});
}
}
Kalau gw sih biasanya kalau ketemu kasus seperti ini akan melakukan try catch dan di dalam scope catch-nya melakukan throws RuntimeException lagi dengan membungkus ulang exception sebelumnya jika ga ada alternatif recovery.
Lombok Sneaky Throws
Alternatifnya adalah dengan dengan menggunakan library Project Lombok.
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
@SneakyThrows
public void printText(String path){
try(FileInputStream fis = new FileInputStream(path)){
int intChar;
while((intChar = fis.read()) != -1){
System.out.print((char) intChar);
}
}
}
public void execute(List<String> paths) throws Exception{
paths.forEach((path) -> printText(path)));
}
Cukup tambahkan @SneakyThrows pada method yang melakukan throws checked exception agar exception tersebut dihandle oleh lombok saat compile.