[英]JMS Exception compile error even though try/Catch block is present
[英]Getting compilation error in main even though try catch finally block is added in the calling method
我正在嘗試運行以下代碼,但由於“未處理的異常類型FileNotFoundException”而出現編譯錯誤,據我的理解,這不應該發生,因為try catch和finally塊已添加到調用方法中。
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Test
{
public static void main(String[] args)
{
myMethod();
}
public static void myMethod() throws FileNotFoundException
{
try
{
System.out.println("In the try block");
FileInputStream fis = new FileInputStream("file.txt");
}
catch(Exception e)
{
System.out.println("in the catch block");
throw e;
}
finally
{
System.out.println("in the finally block");
}
}
}
從myMethod
簽名中刪除throws FileNotFoundException
(然后您需要從catch
塊中刪除throw e;
)。
或者 ,向main
方法添加一個try
and catch
(以處理您指示myMethod
可以拋出的FileNotFoundException
)。
或者 ,向main
的簽名添加throws FileNotFoundException
(正如Andreas在評論中指出的那樣)。
簡而言之,編譯器將不允許您具有未處理的檢查異常的代碼路徑。
在catch
塊中,一旦捕獲到該Exception
,您將再次引發該Exception
。 如果即使在捕獲它后myMethod()
從myMethod()
拋出它,則只需在main方法中添加另一個try-catch即可。
public static void main(String[] args){
try{
myMethod();
}catch(FileNotFoundException e){
System.out.println("catch block in main");
}
}
否則,如果您只想在myMethod()
捕獲Exception
,請不要將其拋出。
try{
System.out.println("In the try block");
FileInputStream fis = new FileInputStream("file.txt");
}
catch(Exception e){
System.out.println("in the catch block");
}
finally{
System.out.println("in the finally block");
}
您可以在以下問題中閱讀有關重新拋出異常的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.