我正在撰寫一個程式來練習拋出例外,并在其中一個測驗中得到編譯錯誤:
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”。誰能解釋一下?
uj5u.com熱心網友回復:
您已經宣告該方法拋出例外 - 它沒有:
public String fileNotFoundExTest() throws FileNotFoundException {
只需更改為:
public String fileNotFoundExTest() {
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/362407.html
上一篇:如何在沒有回溯的例外中引發例外?
