dagger icon indicating copy to clipboard operation
dagger copied to clipboard

Dagger doesn't support constructors that throw

Open diwakergupta opened this issue 12 years ago • 5 comments

Dagger compiler doesn't complain, but compiling the generated class will fail with an error like:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project my-project: Compilation failure
[ERROR] target/generated-sources/annotations/MyClass$$InjectAdapter.java:[66,35] unreported exception FooException; must be caught or declared to be thrown

Seems like this behavior is by design, but it is not documented. So the immediate "fix" would be to document this constraint. Would be nice if the compiler can additionally detect and reject such constructors early.

diwakergupta avatar May 31 '13 18:05 diwakergupta

Well, let me open the question - should we handle these, and wrap, or should we reject them outright? I feel pretty scary about constructors that fail, and I'd say no to them, or wrap them in a @Provides method that handles the failure gracefully, perhaps returning a null-object pattern or some such.

In general, Providers that fail are degenerate from Dagger's point of view, and that includes naturally constructors we wrap in a provider automatically.

cgruber avatar Jun 04 '13 21:06 cgruber

The policy in Dagger 1.0 is to forbid checked exceptions. That's what we should do here, but with nicer error reporting rather than a compile failure in generated code.

We may want to permit these later, but possibly using a different mechanism. Guice has ThrowingProviders; we may want our own hooks that make checked exceptions work with dependency injection.

swankjesse avatar Jun 05 '13 03:06 swankjesse

Hey guys, I'm building my app through the android-maven-plugin but when I include the dagger-compiler (all at v1.0.1) my build fails at the compile stage with;

<blah> ....com/oceanlife/task/DatabaseHelper$$InjectAdapter.java:[56,29] unreported exception
android.content.pm.PackageManager.NameNotFoundException; must be caught or declared to be thrown

Is this a manifestation of the same issue?

BrantApps avatar Jun 30 '13 21:06 BrantApps

Seems quite likely.

cgruber avatar Jul 01 '13 17:07 cgruber

Part of this issue is the fact that the generated "inject adapter" contains a constructor reference to types even if that type is never instantiated through Dagger. That issue is covered by #286, and once fixed will allow constructors that throw to be used as entry points for members-only injection.

JakeWharton avatar Dec 26 '15 06:12 JakeWharton