1

我第一次在 Java 中处理异常,我想知道这是否是个好方法。

public static void main(String[] args) throws FileNotFoundException {
        submethod();        
    }


    static void submethod() throws FileNotFoundException {
        Scanner scan = new Scanner(new File("file.txt"));

        while (scan.hasNextLine()) {
            // do somethig...
        }
    }

对我来说听起来很奇怪的是方法throws FileNotFoundException中的显式声明main,否则编译器会报告:

error: unreported exception FileNotFoundException; must be caught or declared to be thrown

我想知道我是否做错了。在一个更复杂的项目中,你需要捕获更多的异常,它会变得非常混乱。这是处理异常的更好做法吗?为什么我需要在这两种方法中声明它?

4

3 回答 3

2

FileNotFoundException需要在throws子句中指定,因为FileNotFoundException它是一个检查异常。另一种选择是捕获异常并使用try-catch.

由您的程序要求决定如何处理异常。例如,如果您想在抛出异常时打印某个错误消息,您可以捕获它:

try {
    Scanner scan = new Scanner(new File("file.txt"));

    while (scan.hasNextLine()) {
        // do somethig...
    }
} catch(FileNotFoundException ex) {
    System.err.println("file.txt was not found");
}

但是,在像您这样的简单情况下,在发生异常时终止程序是有意义的。因此,您可以像刚才那样声明抛出异常的方法。

在更复杂的场景中,您可能希望捕获异常,向用户打印一些内容,然后继续执行程序。例如,如果submethod仅用于读取用户提供的文件,则可以保持throws原样。但是,该方法的调用者可能希望在异常被抛出时对其进行处理,并且可能要求用户重新输入另一个文件名。

于 2014-12-08T18:26:19.713 回答
0

你不应该这样处理它。您应该在某处捕获错误并处理异常。您应该在 submethod() 中捕获错误或在 main 方法中捕获它并处理异常。您现在拥有的方式没有错误处理,只是将错误抛出堆栈。例子:

static void submethod() {
    try
    {
        Scanner scan = new Scanner(new File("file.txt"));

         while (scan.hasNextLine()) {
            // do somethig...
         }
    }catch(FileNotFoundException e)
    {
        e.printStackTrace();
        //error handling here
    }
}

或者:

public static void main(String[] args) {
    try
    {
         submethod();
    }catch(FileNotFoundException e)
    {
         e.printStackTrace();
         //error handling code here
    }        
}

在第二种情况下,您将在 submethod() 中抛出 FileNotFoundException,即。你会在你的子方法中留下 throws 声明,而不是你的 main 方法,你会在那里处理它。

于 2014-12-08T18:24:28.230 回答
0

由于您的 submethod() 没有处理 FileNotFoundExceptionm 异常。方法的调用者需要处理这个异常,这可以通过将方法调用包含在 try catch 块中或通过将 throws 添加到您的 main 方法来完成。

于 2014-12-08T18:25:27.800 回答