如何解决这个错误?我尝试使用 throws
来 throw
FileNotFoundException
但仍然出现同样的错误。
编译时错误:“默认构造函数无法处理隐式 super 构造函数抛出的异常类型 Exception。必须定义显式构造函数”
代码:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileOne {
Scanner sc = new Scanner(System.in);
String file_name = sc.nextLine();
File obj = new File(file_name);
Scanner reader_obj = new Scanner(obj); // <--- error in this line
public static void main(String args[]) {
FileOne f = new FileOne();
f.create();
f.writeFile();
f.readFile();
}
void create() {
try {
System.out.println("Enter a file name");
if (obj.createNewFile()) {
System.out.println("file name is" + obj.getName());
} else {
System.out.println("Already exists");
}
} catch (IOException e) {
System.out.println("error occured while creating");
}
}
//method to write in file
void writeFile() {
try {
FileWriter w = new FileWriter(obj);
w.write("Learning files now");
w.close();
} catch (IOException e) {
System.out.println("Exception occured while writing a file");
}
}
//method to read
/* use the Scanner class to read the contents of the text file created */
void readFile() {
while (reader_obj.hasNextLine()) {
String data = reader_obj.nextLine();
System.out.println(data);
}
reader_obj.close();
}
}
最佳答案
由默认构造函数隐式调用的 Scanner reader_obj=new Scanner(obj);
行可能会抛出 FileNotFoundException
,这是一个已检查的异常,必须予以处理。
这样做的一种方法是显式定义一个无参数构造函数:
public FileOne() throws FileNotFoundException {
}
不过,如果您打算这样做,为了清楚起见,您应该考虑将成员的初始化移到其中。
关于java - java中与异常处理相关的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63665113/