@PostConstruct & Checked exceptions

前端 未结 3 1791
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-09 14:50

In the @PostConstruct doc it says about the annotated methods:

\"The method MUST NOT throw a checked exception.\"

How would one deal with e.g. an I

相关标签:
3条回答
  • 2020-12-09 15:28

    Generally, if you want or expect application start-up failure when one of your beans throws an exception you can use Lombok's @SneakyThrows.

    It is incredibly useful and succinct when used correctly:

    @SneakyThrows
    @PostConstruct
    public void init() {
        // I usually throw a checked exception
    }
    

    There's a recent write-up discussing its pros and cons here: Prefer Lombok’s @SneakyThrows to rethrowing checked exceptions as RuntimeExceptions

    Enjoy!

    0 讨论(0)
  • 2020-12-09 15:37

    Yes, wrap it in a runtime exception. Preferebly something more concrete like IllegalStateException.

    Note that if the init method fails, normally the application won't start.

    0 讨论(0)
  • 2020-12-09 15:42

    Use a softened exception like so, in effect wrapping in RuntimeException: https://repl.it/@djangofan/SoftenExceptionjava

    private static RuntimeException softenException(Exception e) {
        return checkednessRemover(e);
    }
    private static <T extends Exception> T checkednessRemover(Exception e) throws T {
        throw (T) e;
    }
    

    Then usage is like:

    } catch (IOException e) {
            throw softenException(e);
            //throw e; // this would require declaring 'throws IOException'
    }
    
    0 讨论(0)
提交回复
热议问题