错误与Java中的异常处理有关

huangapple go评论64阅读模式
英文:

error related to exception handling in java

问题

如何解决这个错误我尝试使用`throws`来抛出`FileNotFoundException`,但错误仍然相同

编译时错误"默认构造函数无法处理隐式超级构造函数抛出的异常类型。必须定义显式构造函数。"

代码

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); // <--- 此行出错
    
    public static void main(String args[]) {
        FileOne f = new FileOne();
        f.create();
        f.writeFile();
        f.readFile();
    }
    
    void create() {
        try {
            System.out.println("输入文件名");
            if (obj.createNewFile()) {
                System.out.println("文件名为" + obj.getName());
            } else {
                System.out.println("已存在");
            }
        } catch (IOException e) {
            System.out.println("创建时发生错误");
        }
    }
    
    // 写入文件的方法
    void writeFile() {
        try {
            FileWriter w = new FileWriter(obj);
            w.write("现在正在学习文件");
            w.close();
        } catch (IOException e) {
            System.out.println("写入文件时发生异常");
        }
    }
    
    // 读取文件的方法
    /* 使用Scanner类读取创建的文本文件的内容 */
    void readFile() {
        while (reader_obj.hasNextLine()) {
            String data = reader_obj.nextLine();
            System.out.println(data);
        }
        reader_obj.close();
    }
}
英文:

How to resolve this error? I have tried using throws to throw FileNotFoundException but still same error.

Compile-Time Error : "Default constructor cannot handle exception type Exception thrown by the implicit super constructor. Must define an explicit constructor "

CODE :

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); // &lt;--- 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(&quot;Enter a file name&quot;);
if (obj.createNewFile()) {
System.out.println(&quot;file name is&quot; + obj.getName());
} else {
System.out.println(&quot;Already exists&quot;);
}
} catch (IOException e) {
System.out.println(&quot;error occured while creating&quot;);
}
}
//method to write in file
void writeFile() {
try {
FileWriter w = new FileWriter(obj);
w.write(&quot;Learning files now&quot;);
w.close();
} catch (IOException e) {
System.out.println(&quot;Exception occured while writing a file&quot;);
}
}
//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();
}
}

答案1

得分: 1

Scanner reader_obj = new Scanner(obj); 这一行代码在默认构造函数中隐式调用,可能会抛出一个受检异常 FileNotFoundException,必须进行处理。

一种处理的方式是显式定义一个无参构造函数:

public FileOne() throws FileNotFoundException {
}

不过,如果你这样做的话,出于清晰起见,你应该考虑将成员变量的初始化也移到这个构造函数中。

英文:

The line Scanner reader_obj=new Scanner(obj);, which is implicitly called by the default constructor, may throw a FileNotFoundException, which is a checked exception and must be handled.

One way of doing so is explicitly defining a no-arg constructor:

public FileOne() throws FileNotFoundException {
}

Although, if you're going to do that, you should consider moving the members' initialization in to it for clarity's sake.

答案2

得分: 1

错误已解决:

  1. 我在 main()reading() 方法中使用了 throws 来抛出异常。
  2. 使用了 FileReader 类来从给定的输入文件中读取数据

最终代码:

public class FileOne {
    Scanner sc = new Scanner(System.in);
    String file_name = sc.nextLine();
    File obj = new File(file_name);

    // 用于创建文件的方法
    void create() {
        try {
            if (obj.createNewFile()) {
                System.out.println("文件名为:" + obj.getName());
            } else {
                System.out.println("已存在");
            }
        } catch (IOException e) {
            System.out.println("创建文件时出错");
        }
    }
    
    // 用于写入文件的方法
    void writeFile() {
        try {
            FileWriter w = new FileWriter(obj);
            w.write("现在学习文件");
            w.close();
        } catch (IOException e) {
            System.out.println("写入文件时出现异常");
        }
    }
    
    void reading() throws FileNotFoundException, IOException {
        FileReader reader = new FileReader(file_name);
        int i;
        while ((i = reader.read()) != -1) {
            System.out.print((char) i);
        }
        reader.close();
    }

    public static void main(String args[]) throws FileNotFoundException, IOException {
        FileOne f = new FileOne();
        f.create();
        f.writeFile();
        f.reading();
    }
}

请注意,翻译只针对代码部分,不包括您提供的说明性文本。如果您需要进一步的帮助,请随时提问。

英文:

Errors Resolved:

  1. I used throws to throw exceptions in main() and reading() method.
  2. Used FileReader class to read the data from the given input file

Final Code:

public class FileOne {
Scanner sc=new Scanner(System.in);
String file_name=sc.nextLine();
File obj=new File(file_name);
//method for creating a file
void create(){
try{
if(obj.createNewFile()){
System.out.println(&quot;file name is&quot;+obj.getName());
}
else{
System.out.println(&quot;Already exists&quot;);
}
}
catch(IOException e){
System.out.println(&quot;error occured while creating&quot;);
}    
}
//method to write in file
void writeFile(){
try{
FileWriter w=new FileWriter(obj);
w.write(&quot;Learning files now&quot;);
w.close();
}
catch(IOException e){
System.out.println(&quot;Exception occured while writing a file&quot;);
}
}
void reading() throws FileNotFoundException,IOException{
FileReader reader=new FileReader(file_name);
int i;
while((i=reader.read())!=-1){
System.out.print((char)i);
}
reader.close();
}
public static void main(String args[])throws FileNotFoundException,IOException{
FileOne f=new FileOne();
f.create(); 
f.writeFile();
f.reading();  
}
}

答案3

得分: 0

添加如下构造函数:

public FileOne() throws FileNotFoundException {

}

将您的 void main() 编辑如下(您还需要从 main 方法中抛出异常):

public static void main(String args[]) throws FileNotFoundException {
    FileOne f = new FileOne();
    f.create();
    f.writeFile();
    f.readFile();
}
英文:

Add the constructor as below :

public FileOne () throws FileNotFoundException {
}

Edit your void main () as below (You need to throw the exception from main as well) :

public static void main(String args[]) throws FileNotFoundException {
FileOne f = new FileOne();
f.create();
f.writeFile();
f.readFile();
}

huangapple
  • 本文由 发表于 2020年8月31日 13:11:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/63665113.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定