Yes, the abstract methods of an interface can throw an exception.
In the following example the interface (MyInterface) contains an abstract method with name display, which throws an IOException.
import java.io.IOException; abstract interface MyInterface { public abstract void display()throws IOException ; }
You need to follow the rules given below while implementing such method −
If the abstract method in the interface throws certain exception. The implemented method can throw the same exception as shown below −
import java.io.IOException; abstract interface MyInterface { public abstract void display()throws IOException ; } public class InterfaceExample implements MyInterface{ public void display()throws IOException { System.out.println("This is the subclass implementation of the display method"); } public static void main (String args[]){ try { new InterfaceExample().display(); } catch (Exception e) { e.printStackTrace(); } } }
This is the subclass implementation of the display method
If the abstract method in the interface throws certain exception. The implemented method can choose not to throw any exception as shown below −
import java.io.IOException; abstract interface MyInterface { public abstract void display()throws IOException ; } public class InterfaceExample implements MyInterface{ public void display() { System.out.println("This is the subclass implementation of the display method"); } public static void main (String args[]){ try { new InterfaceExample().display(); } catch (Exception e) { e.printStackTrace(); } } }
This is the subclass implementation of the display method
If the abstract method in the interface throws certain exception. The implemented method can throw its subtype −
import java.io.IOException; abstract interface MyInterface { public abstract void display()throws Exception ; } public class InterfaceExample implements MyInterface{ public void display()throws IOException { System.out.println("This is the subclass implementation of the display method"); } public static void main (String args[]){ try { new InterfaceExample().display(); } catch (Exception e) { e.printStackTrace(); } } }
This is the subclass implementation of the display method
If the abstract method in the interface throws certain exception. The implemented method should not throw its super type
import java.io.IOException; abstract interface MyInterface { public abstract void display()throws IOException ; } public class InterfaceExample implements MyInterface{ public void display()throws Exception { System.out.println("This is the subclass implementation of the display method"); } public static void main (String args[]){ try { new InterfaceExample().display(); } catch (Exception e) { e.printStackTrace(); } } }
InterfaceExample.java:8: error: display() in InterfaceExample cannot implement display() in MyInterface public void display()throws Exception { ^ overridden method does not throw Exception 1 error