Java接口中的抽象方法可以抛出异常吗?


是的,接口的抽象方法可以抛出异常。

示例

在下面的示例中,接口 (MyInterface) 包含一个名为 *display* 的抽象方法,该方法抛出 IOException 异常。

import java.io.IOException;
abstract interface MyInterface {
   public abstract void display()throws IOException ;
}

遵循的规则

实现此类方法时,需要遵循以下规则:

  • 如果接口中的抽象方法抛出某种异常,则实现方法可以抛出与之相同的异常,如下所示:

示例1

 在线演示

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
  • 如果接口中的抽象方法抛出某种异常,则实现方法可以选择不抛出任何异常,如下所示:

示例2

 在线演示

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
  • 如果接口中的抽象方法抛出某种异常,则实现方法可以抛出其子类型:

示例3

 在线演示

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
  • 如果接口中的抽象方法抛出某种异常,则实现方法不应抛出其超类型

示例4

 在线演示

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

更新于:2020年6月29日

2K+ 浏览量

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.