0

我很确定这是一个简单的问题,但我找不到直接的答案。如何使用 调用方法throws FileNotFoundException

这是我的方法:

private static void fallingBlocks() throws FileNotFoundException
4

6 回答 6

8

你调用它,或者声明你的方法也抛出它,或者捕获它:

public void foo() throws FileNotFoundException // Or e.g. throws IOException
{
    // Do stuff
    fallingBlocks();
}

或者:

public void foo()
{
    // Do stuff
    try
    {
        fallingBlocks();
    }
    catch (FileNotFoundException e)
    {
        // Handle the exception
    }
}

有关更多详细信息,请参阅Java 语言规范的第 11.2 节有关异常的 Java 教程

于 2011-09-27T12:17:07.507 回答
3

您只需像调用任何其他方法一样调用它,并确保您要么

  1. FileNotFoundException在调用方法中捕获和处理;
  2. 确保调用方法在其列表中具有FileNotFoundException或其超类。throws
于 2011-09-27T12:17:20.377 回答
3

您只需catch抛出异常或重新抛出它。阅读有关异常的信息。

于 2011-09-27T12:17:26.537 回答
2

不确定我是否收到您的问题,只需调用该方法:

try {
    fallingBlocks();
} catch (FileNotFoundException e) {
    /* handle */
}
于 2011-09-27T12:17:18.593 回答
2

You call it like any other method too. However the method might fail. In this case the method throws the exception. This exception should be caught with a try-catch statement as it interrupts your program flow.

于 2011-09-27T12:24:10.533 回答
2

是不是像调用普通方法一样。唯一的区别是您必须通过在 try..catch 中包围它或通过从调用方方法抛出相同的异常来处理异常。

try {
    // --- some logic
    fallingBlocks();
    // --- some other logic
} catch (FileNotFoundException e) {
    // --- exception handling
}

或者

public void myMethod() throws FileNotFoundException {
    // --- some logic
    fallingBlocks();
    // --- some other logic
}
于 2011-09-27T12:18:54.740 回答