public class s1 {
void m1(){
m2();
}
String m2() throws IOException{
BufferedReader inputFile = new BufferedReader(new FileReader("a.txt"));
String line = inputFile.readLine();
inputFile.close();
return line;
}
}
public class Main {
public static void main(String[] args) {
s1 obj1 = new s1();
try {
obj1.m1();
}
catch (Exception e){
System.out.println("I got it!");
}
}
}
当我运行这段代码,我从main方法的检查异常
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type IOException
我感到困惑的是消息,因为我认为我处理这个检查IOException异常的主要方法处理。然而,编译器希望我也将throws
添加到void m1()
。这样做的主要原因是什么?
每一个方法调用平方米必须确定它是如何HANDELS是例外。那确实包括m1。 –
'm1'调用'm2','m2'抛出'IOException'。但'm1'不处理异常,因此您必须选择:make'm1'引发异常,或为'm2'调用添加'try/catch'块 –
与'm2'完全相同捕获或声明抛出可能在其调用的方法中发生的'IOException'(例如'readLine()'),'m1'也必须执行相同的操作,因为它会调用一个方法('m2()') IOException'。 – Berger