java - java中与异常处理相关的错误

标签 java exception compiler-errors

如何解决这个错误?我尝试使用 throwsthrow 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/

相关文章:

swift - 类型不符合协议(protocol) 'AVCaptureFileOutputRecordingDelegate'

java - 本地主机上的 JBoss 服务器连接被拒绝 :1099

java - 将java中控制台的输出写入文本文件

java - 在 Java 中总是忽略调用 Thread sleep() 的 InterruptedException 是否安全

symfony - Symfony 验证器的注释返回 "annotation was never imported exception"

ASP.NET – 错误抛出或记录

python - 尝试编译扩展类型时出现 CompileError

java - 如何获取 Lucene(5.3) 生成的特定术语的位置

java - 将大对象引用而不是小对象传递给方法在处理或内存消耗方面有什么不同吗?

c - 结构体编译时错误