javainterface

Handling exceptions in interface in java


I want to ask is it a good practice or advisable to handle exceptions in an interface? For example:

 public interface myInterface{
  String readFile() throws IOException;
  String printValues() throws IOException;
}

is this a good way to handle exceptions?


Solution

  • An interface method in Java can declare that a method throws a particular exception. This is a best practice (when not overused) since the interface defines what class of exception can be thrown.

    Checked exceptions by design require the caller to use try-catch or declare throws on the method. If a method in an interface does not declare an exception then an implementation of that interface cannot override the method and throw a checked exception. Implementation classes throwing unchecked exceptions (RuntimeException or their subclasses) could become potential errors downstream if not properly documented or understood.

    For commonly occurring exceptions it is best practice to declare the exception in the interface. Many of the java.io interfaces follow this practice.

    Example:

    public interface Closeable {
    
      void close() throws IOException;
    
    }
    

    For more details see this tutorial discussing checked vs unchecked exceptions. https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html

    See related question:
    Handling exceptions with interfaces and classes in java