Java Lombok | Automatically Handling throws - @SneakyThrows

@SneakyThrows

If you declare the @SneakyThrows annotation on a method, you do not need to add throws even when a checked exception occurs inside the method.

  • sneaky means “secretly” or “stealthily.”
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");
    }
}

Execution result:

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)

Ignoring Only Specified Exceptions

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();
    }
}

Execution result:

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)
  • By passing an exception class object as value, you can ignore only the specified exception.