在Java中,重写方法时,能否将throws子句中声明的异常类型从非检查型异常改为检查型异常?
检查型异常是在编译时发生的异常,也称为编译时异常。在编译时不能简单地忽略这些异常;程序员应该处理这些异常。
非检查型异常是在运行时发生的异常,也称为运行时异常。这些异常包括编程错误,例如逻辑错误或API的错误使用。在编译时会忽略运行时异常。
非检查型异常到检查型异常
当超类中的方法抛出非检查型异常时,子类中重写该方法不能抛出检查型异常。
示例
在下面的示例中,名为Super的类中有一个抽象方法,该方法抛出非检查型异常(ArithmeticException)。
在子类中,我们重写了此方法并抛出检查型异常(IOException)。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.io.InvalidClassException;
abstract class Super {
public abstract String readFile(String path) throws ArithmeticException;
}
public class ExceptionsExample extends Super {
@Override
public String readFile(String path) throws FileNotFoundException {
// TODO Auto-generated method stub
return null;
}
}输出
ExceptionsExample.java:12: error: readFile(String) in ExceptionsExample cannot
override readFile(String) in Super
public String readFile(String path) throws FileNotFoundException {
^
overridden method does not throw FileNotFoundException
1 error但是,当超类中的方法抛出检查型异常时,子类中重写该方法可以抛出非检查型异常。
示例
在下面的示例中,我们只是交换了超类和子类中方法的异常。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.io.InvalidClassException;
abstract class Super{
public abstract String readFile(String path) throws FileNotFoundException ;
}
public class ExceptionsExample extends Super {
@Override
public String readFile(String path) throws ArithmeticException {
// TODO Auto-generated method stub
return null;
}
}如果编译上面的程序,它会在没有编译时错误的情况下编译。
输出
Error: Main method not found in class ExceptionsExample, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP