我很确定这是一个简单的问题,但我找不到直接的答案。如何使用 调用方法throws FileNotFoundException
?
这是我的方法:
private static void fallingBlocks() throws FileNotFoundException
我很确定这是一个简单的问题,但我找不到直接的答案。如何使用 调用方法throws FileNotFoundException
?
这是我的方法:
private static void fallingBlocks() throws FileNotFoundException
你调用它,或者声明你的方法也抛出它,或者捕获它:
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 教程。
您只需像调用任何其他方法一样调用它,并确保您要么
FileNotFoundException
在调用方法中捕获和处理;FileNotFoundException
或其超类。throws
您只需catch
抛出异常或重新抛出它。阅读有关异常的信息。
不确定我是否收到您的问题,只需调用该方法:
try {
fallingBlocks();
} catch (FileNotFoundException e) {
/* handle */
}
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.
是不是像调用普通方法一样。唯一的区别是您必须通过在 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
}