簡體   English   中英

即使在調用方法中添加了try catch finally塊,也仍然在main中獲得編譯錯誤

[英]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");
}

您可以在以下問題中閱讀有關重新拋出異常的更多信息。

重新拋出Java中的異常

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM