Java – Dagger does not like constructors that throw exceptions

Dagger does not like constructors that throw exceptions… here is a solution to the problem.

Dagger does not like constructors that throw exceptions

I’m trying to use Dagger in my android app to simplify dependency injection. It looks like Dagger 2.0 doesn’t support constructors that throw exceptions. Is there a solution?

Refactoring and creating an init method that throws an exception doesn’t seem feasible because having to call init on the entire chain of dependent objects reintroduces the problem that dagger solves.

Solution

The generated code is not clear what should happen when an exception is thrown during constructor. Should classes that depend on such instances be required to catch exceptions somehow? Should the application crash if an exception is thrown? Often, dependency injection attempts to separate dependent classes from the construction strategy of their dependencies, which would violate that principle.

One choice is which @Provides instance to use @Module. Then, if an exception is thrown, i.e. @Provides method can return a reasonable default value. You might also consider using the Optional <> to indicate that the object cannot be constructed correctly.

Related Problems and Solutions