Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing an Exception Not Defined in the Interface

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.

like image 530
Scott Avatar asked Aug 03 '09 16:08

Scott


2 Answers

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

... catch(CupcakeException e) {
   throw new IOException("The sky is falling", e);
 }
like image 182
Thorbjørn Ravn Andersen Avatar answered Oct 13 '22 04:10

Thorbjørn Ravn Andersen


Use something called ReaderException that will serve as the root interface of your exception hierarchy. ReaderException will also provides a link to other exceptions that get thrown due to lower level exceptions.

like image 27
Srikar Doddi Avatar answered Oct 13 '22 03:10

Srikar Doddi