我是一名Java初学者并且已经阅读了类似的问题,但我仍然不知道为什么我的代码显示了FileNotFound异常。 我的文件在同一目录中。
我的代码是:
import java.io.*;
import java.util.Scanner;
public class reader {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
double y = in.nextDouble();
float g = in.nextFloat();
String a = in.next();
File file = new File("v.txt");
System.out.println(x + "" + y + "" + g + "" + a);
Scanner inFile = new Scanner(new FileReader(file));
String u = inFile.nextLine();
System.out.println(file.getAbsolutePath());
System.out.println(u);
}
}
错误是:
17: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
Scanner inFile = new Scanner(new FileReader(file));
^
1 error
答案 0 :(得分:6)
您遇到编译时错误:
error: unreported exception FileNotFoundException; must be caught or declared to be thrown
Scanner inFile = new Scanner(new FileReader(file));
这是修复它的一种简单方法:
public class reader {
public static void main(String[] args) throws Exception {
//...
}
}
虽然使用try {...} catch(...){}是处理可能的运行时异常的更好方法。