gpt4 book ai didi

java - 文件扫描器 : Unreported exception FileNotFoundException; must be caught or declared to be thrown

转载 作者:行者123 更新时间:2023-12-01 22:46:35 25 4
gpt4 key购买 nike

我已经尝试了我在 Internet 上可以找到的所有方法,但似乎没有任何方法可以解决此问题。我正在寻求帮助,告诉我我做错了什么。我是 Java 的新手。谢谢!

import java.util.Scanner;

class File_Scanner {
public static void read() {
File credentials_file = new File("credentials.txt");
Scanner file_reader = new Scanner(credentials_file);
String[] users = new String[6];
int index_counter = 0;

try {
while (file_reader.hasNextLine()) {
users[index_counter] = file_reader.nextLine();
}
file_reader.close();

} catch (Exception e) {
System.out.println(e.getClass());
}
}
}

这显示了以下错误

Unreported exception FileNotFoundException; must be caught or declared to be thrown

最佳答案

我建议用 try/catch block 围绕整个 read 函数,如下所示。

import java.util.Scanner;

class File_Scanner{
public static void read(){
try {
File credentials_file = new File("credentials.txt");
Scanner file_reader = new Scanner(credentials_file);
String[] users = new String[6];
int index_counter = 0;

while (file_reader.hasNextLine()) {
users[index_counter] = file_reader.nextLine();
}

file_reader.close();
} catch (Exception e) {
System.out.println(e.getClass());
}
}
}

try/catch 的想法是避免在运行程序时可能发生的任何错误。在您的情况下,如果未找到或删除 credentials_fileScanner file_reader = new Scanner(credentials_file); 可能会引发错误。因此,您需要在 try block 周围覆盖它,这将为您提供一个异常,可以处理该异常以在 catch block 中显示正确的响应消息。

希望对您有所帮助!

关于java - 文件扫描器 : Unreported exception FileNotFoundException; must be caught or declared to be thrown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54796905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com