@PostConstruct & Checked exceptions

风流意气都作罢 提交于 2019-11-29 01:01:00

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.

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!

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'
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!