如何忽略在你的Java代码中抛出的异常(附实例)

1,822 阅读1分钟

有时,你可能想忽略一个由你的Java程序抛出的异常而不停止程序的执行。

要在Java中忽略一个异常,你需要在可以抛出异常的代码中加入try...catch 块,但你不需要在catch 块中写任何东西。

让我们看一个如何做到这一点的例子。

假设你有一个checkAge() 方法,检查你代码中的age 变量是否大于18 ,如下所示:

static void checkAge(int age) throws Exception {
if (age < 18) {
throw new Exception( "Age must be greater than 18" );
}
}

在你的main() 方法中,你可以用一个try...catch 块包围对checkAge() 方法的调用。

catch 块的参数应该被命名为ignored ,以便让Java知道这个异常被忽略:

public static void main(String[] args) {
try {
checkAge(15);
 } catch (Exception ignored) { }

System.out.println("Ignoring the exception");
System.out.println("Continue code as normal");
}

当异常发生时,上面的catch 块被执行,Java不会做任何事情。

异常被忽略,catch 块下面的下一行代码将被执行,就像什么都没有发生一样。

输出:

Ignoring the exception
Continue code as normal
Process finished with exit code 0

当你有多个要忽略的异常时,你需要把try...catch 块放在每个异常中,如下所示:

try {
checkAge(12);
} catch (Exception ignored) { }
try {
checkAge(15);
} catch (Exception ignored) { }
try {
checkAge(16);
} catch (Exception ignored) { }

上面的代码很快就变得冗长了。你可以通过创建一个包装方法来优化代码,该方法为你的可运行函数准备了try...catch 块。

你需要创建一个功能接口,作为你想忽略的方法的类型。

考虑一下下面的ignoreExc() 函数:

static void ignoreExc(Runnable r) {
try {
r.run();
} catch (Exception ignored) { }
}
@FunctionalInterface
interface Runnable {
void run() throws Exception;
}

ignoreExc() 函数内调用run() 方法将执行你传入该方法的Runnable

最后,你只需要使用ignoreExc() 函数,用lambda表达式来调用你的实际方法,如下所示:

public static void main(String[] args) {
 ignoreExc(() -> checkAge(16));
 ignoreExc(() -> checkAge(17));
 ignoreExc(() -> checkAge(18));

System.out.println("Ignoring the exception");
System.out.println("Continue code as normal");
}

checkAge() 方法的异常将被忽略,因为在ignoreExc() 函数的catch 块中没有任何东西。

有了ignoreExc() 函数,你就减少了每次想忽略一个异常时用try...catch 块来包裹你的代码的需要。

下面是Java中忽略异常的完整代码:

class Main {
public static void main(String[] args) {
ignoreExc(() -> checkAge(16));
ignoreExc(() -> checkAge(17));
ignoreExc(() -> checkAge(18));
System.out.println("Ignoring the exception");
System.out.println("Continue code as normal");
}
static void checkAge(int age) throws Exception {
if (age < 18) {
throw new Exception("Age must be greater than 18");
}
}
static void ignoreExc(Runnable r) {
try {
r.run();
} catch (Exception ignored) { }
}
@FunctionalInterface
interface Runnable {
void run() throws Exception;
}
}

现在你已经学会了如何忽略Java程序抛出的异常。

欢迎在你的项目中使用本教程中的代码。👍