[英]unreported IOException even though in try-catch block and throws Exception
[英]unreported exception despite of try-catch block
我正在编写一个程序来练习抛出异常,并在其中一个测试中得到编译错误:
MyTest.java:29: 错误:未报告的异常 FileNotFoundException; 必须被捕获或声明被抛出:
Assert.assertEquals("找不到文件", task2.fileNotFoundExTest());
^
public void fileNotFoundEx() throws FileNotFoundException {
File fileName = new File("foo.txt");
BufferedReader rd = new BufferedReader(new FileReader(fileName));
}
public String fileNotFoundExTest() throws FileNotFoundException {
try {
fileNotFoundEx();
} catch (FileNotFoundException e) {
return "File Not Found";
}
return "No Error";
}
我不知道为什么会发生此错误,因为我已经将导致异常的方法放在 try-catch 块中,并为这两种方法添加了签名“throws FileNotFoundException”。 谁能解释一下?
您已经声明该方法抛出异常 - 它没有:
public String fileNotFoundExTest() throws FileNotFoundException {
只需更改为:
public String fileNotFoundExTest() {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.