Throwing an Exception Not Defined in the Interface

Scott picture Scott · Aug 3, 2009 · Viewed 10.7k times · Source

What is the best practice to follow when you need to throw an exception which was not defined in an interface that you are implementing?

Here is an example:

public interface Reader
{
    public abstract void read() throws IOException;
}

public class CarrotReader implements Reader
{
    public void read() throws IOException {}
}

public class CupcakeReader implements Reader
{
    public void read() throws IOException, CupcakeException {}
}

In this case, you have a specific exception that occurs when reading cupcakes, so you want to throw an exception related to this. However, Reader doesn't define this type of exception in its interface, so what do you do? Furthermore, it doesn't make sense to add CupcakeException to the throws clause in the Reader interface, because this type of exception is specific to CupcakeReader. One way around this is to have Reader define read such that it throws some parent type, like Exception, but then you lose the context for the exception. What should you do in this situation? Thanks!


Another interesting situation that has been brought up involves an interface over which you have no control. In this case, what is the best way to indicate that a problem has occurred?

For illustrative purposes, here is another example:

public interface Reader
{
    public abstract void read();
}

public class CupcakeReader implements Reader
{
    public void read() throws CupcakeException {}
}

In this case, you cannot change Reader, but you want to indicate that a problem has occurred in CupcakeReader's read method.

Answer

Thorbjørn Ravn Andersen picture Thorbjørn Ravn Andersen · Aug 3, 2009

You may have to create an exception of the expected type instead.

... catch(CupcakeException e) {
   throw new IOException("The sky is falling", e);
 }