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 IOException which can be thrown in such a method? Just wrap it in a RuntimeException and let the user worry about the faulty initial state of the object? Or is @PostConstruct the wrong place to validate and initialize objects which got their dependencies injected?
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:
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
Then usage is like: