编译器如何知道在执行之前要抛出的异常?

Und*_*Dog 3 java

import java.io.*;
class ex3
{

    public static void main(String args[])
    {
       myfun();
    }

    static void myfun()
    {
        try
        {
           FileInputStream f = new FileInputStream("file.ytxt");
           System.out.println("my fun");
        }

        catch(Exception e) //Line 1
        {
           System.out.println(e.getMessage());
        }

        catch(FileNotFoundException e) //Line 2
        {
           System.out.println("File Not Found Caught");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我创建了两个异常处理程序代码(一个是通用的,另一个是第1行和第2行).

我的编译器在抱怨

ex3.java:24: error: exception FileNotFoundException has already been caught
                catch(FileNotFoundException e)
                ^
1 error
Run Code Online (Sandbox Code Playgroud)

我的问题是编译器是如何知道try块会抛出"FileNotFoundException"的?

Mar*_*oun 10

catch(FileNotFoundException e)这条线无法到达.以来:

FileNotFoundException extends Exception

请参见ExceptionFileNotFoundException:

在此输入图像描述

您可能想要切换订单.


Pet*_*sik 6

你的问题出在其他地方.FileNotFoundException将始终被捕获,Exception因为这是所有异常的基类.所以编译器基本上抱怨一段死代码

catch(FileNotFoundException e) {
    System.out.println("File Not Found Caught");
}
Run Code Online (Sandbox Code Playgroud)

一般来说,抓住它并不是一个好主意Exception,你应该总是尝试进行更细粒度的expcetion处理,所以删除它并且只留下FileNotFoundException