这是在运行Java的时候常遇见的问题:
报错信息:Default constructor cannot handle exception type FileNotFoundException thrown by implicit super constructor. Must define an explicit constructor。
意思是:默认的构造函数不能处理隐式超级构造函数引发的异常类型 FileNotFoundException,必须定义显式构造函数。
具体情形:在测试RandomAccessFile这个类的使用方法时
声明了一个RandomAccessFile类型【全局变量】。
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
public class MyRandomAccessFile {
private RandomAccessFile file = new RandomAccessFile("D:/demo/test.txt", "rw");
}
然后搜了一下,都在放屁。
我查看了一下RandomAccessFile的构造函数的API:
public RandomAccessFile(String name,String mode)throws FileNotFoundException
FileNotFoundException - if the mode is "r" but the given string does not denote an existing regular file,
or if the mode begins with "rw" but the given string does not denote an existing, writable regular file and a new regular file of that name cannot be created,
or if some other error occurs while opening or creating the file
我先是查了下隐式构造函数转显示构造函数的方法,然后查了下这个错误的详细信息,木有。
最后看到API才明白:原来是这个方法的构造函数中声明了
这样我们就没法直接使用这个方法,因为类名是无法声明throws的,所以:
1. 新建一个方法,将此RandomAccessFile作为返回值类型,并声明throws。
public RandomAccessFile createRAFByfilename(String filename,String mode)throws FileNotFoundException{
return new RandomAccessFile(filename, mode);
}
2. 直接在要新建RandomAccessFile 对象的方法上,声明throws。
public static void main() throws FileNotFoundException {
MyRandomAccessFile mraf = new MyRandomAccessFile();
RandomAccessFile file = mraf.createRAFByfilename("D:/demo/test.txt", "rw");
}
总之就是和隐式和显式构造函数没什么鸟关系。