square / dagger

A fast dependency injector for Android and Java.
https://square.github.io/dagger/
Apache License 2.0
7.31k stars 3.06k forks source link

Dagger doesn't support constructors that throw #266

Open diwakergupta opened 11 years ago

diwakergupta commented 11 years ago

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.

cgruber commented 11 years ago

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.

swankjesse commented 11 years ago

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.

BrantApps commented 11 years ago

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?

cgruber commented 11 years ago

Seems quite likely.

JakeWharton commented 8 years ago

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.