Reputation: 267020
Inside my class I have a private variable that my methods use which has an exception that has to be caught.
How can I force the callee to handle the exception and not have me do it in my code?
public class SomeLibImpl extends SomeLib {
private Mongo _mongo = new Mongo();
}
Where Mongo throws a UnknownHostException
that I have to handle.
If this is something I shouldn't be doing and there is a better way please tell me, but I also want to know how to force the callee of the class to handle the exception.
I thought I would do this:
public class SomeLibImpl extends SomeLib throws UnknownHostException {
// ..
}
But that doesn't compile.
Upvotes: 2
Views: 8571
Reputation: 28568
Just add this to your class
public SomeLibImpl() throws UnknownHostException {
}
Upvotes: 2
Reputation: 12883
Either you should initialize mongo in your constructor, and put the throws clause on the constructor, or you should pass it in to the constructor (inject it).
e.g.
public class Foo extends Bar {
private Mongo mongo;
public Foo() throws SomeException {
mongo = new Mongo();
}
// stuff goes here
}
Or you can inject the object into yours...
public class Foo extends Bar {
private Mongo mongo;
public Foo(Mongo mongo) {
this.mongo = mongo;
}
// stuff goes here
}
The second style of object construction (dependency injection) is better than initializing in the class, because it allows you to substitute other objects if you want to perform tests on the object but don't want to have to depend on a database to do so, then you can inject a stub (or mock) version of the object and test your object in isolation.
Also, you can't force users of your class to handle exceptions that your code throws. Even if you throw a checked exception, they can ignore it or simply declare that their method throws the exception too, which passes the buck to whatever code calls them.
Upvotes: 2
Reputation: 9317
You can initialize the field in constructor and make the constructor throw a checked exception.
Upvotes: 1
Reputation: 54074
You need to know the difference of checked
vs unchecked exceptions.
Use checked exceptions to force the caller of the method to handle the exception.
You are forcing him since if the calling code does not handle the exception it will not compile (unlike unchecked exceptions)
In your case declaring a throws
with a checked exception in your method will do that.
Upvotes: 2
Reputation: 23171
Using throws
is what you need to do to force the caller to handle the exception. Your problem is that you put it on your class declaration. Methods can throw exceptions, classes can't.
Upvotes: 5
Reputation: 42849
You add the throws
keyword to the method signature, not the class definition.
public class SomeLibImpl extends SomeLib {
public void someMethod() throws UnknownHostException {
//
}
}
Upvotes: 1