I am trying to add a custom throws clause to a method definied by an interface. This is not possible. How could I bypass it? Here is some code:
private void sendRequestToService(final ModuleRequest pushRequest)
{
ServiceConnection serviceConnection = new ServiceConnection()
{
public void onServiceConnected(ComponentName name, IBinder service)
{
try
{
//some lines..
} catch (RemoteException e)
{
throw new RuntimeException(new UnavailableDestException()) ;
}
}
};
}
Any idea how I could throw my custom exception?
There are two types of exceptions, checked and unchecked. Any
Throwableis either one or the other.An example of a checked exception is
IOException; probably the most (in)famous unchecked exception isNullPointerException.Any checked exceptions that a method may
throwmust be declared in itsthrowsclause. When you@Overridea method (either implementing aninterfacemethod or overriding an inherited method from a superclass), certain requirements must be met, and one of them is that thethrowsclause must not cause a conflict. Simplistically speaking, subclasses/implementations can throw LESS, not MORE checked exceptions.An unchecked exception is defined as
RuntimeExceptionand its subclasses, andErrorand its subclasses. They do not have to be declared in a method’sthrowsclause.So in this particular case, if you want to
throwaCustomExceptionin an implementation of aninterfacemethod that does not list it in itsthrowsclause, you can makeCustomException extends RuntimeException, making it unchecked. (It can alsoextendsany subclass ofRuntimeException, e.g.IllegalArgumentExceptionorIndexOutOfBoundsExceptionmay be more appropriate in some cases).This will allow you to compile the code as you desire, but note that the choice between choosing checked vs unchecked exception should not be taken too lightly. This is a contentious issue for many, and there are many factors to consider other than just getting the code to compile the way you want it. You may want to consider a redesign of the
interfacerather than having implementors throwing various undocumented unchecked exceptions not specified by theinterfacecontract.References
Related questions
See also
Workaround “solution”
If a redesign is impossible, then wrapping your
CustomExceptionin aRuntimeException(or its subclass) will “work”. That is, instead of:You can, should you insist, do the following:
It needs to be reiterated that this is NOT a recommendable technique in general. You should fix the problem at the design level if at all possible, but barring that, this is indeed a possible workaround.