繁体   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