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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP