我第一次在 Java 中处理异常,我想知道这是否是个好方法。
public static void main(String[] args) throws FileNotFoundException {
submethod();
}
static void submethod() throws FileNotFoundException {
Scanner scan = new Scanner(new File("file.txt"));
while (scan.hasNextLine()) {
// do somethig...
}
}
对我来说听起来很奇怪的是方法throws FileNotFoundException
中的显式声明main
,否则编译器会报告:
error: unreported exception FileNotFoundException; must be caught or declared to be thrown
我想知道我是否做错了。在一个更复杂的项目中,你需要捕获更多的异常,它会变得非常混乱。这是处理异常的更好做法吗?为什么我需要在这两种方法中声明它?