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.
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.
Or you can inject the object into yours…
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.