试试......抓住......最后

try { ... } catch ( ... ) { ... } 控制结构用于处理异常

String age_input = "abc";
try {
    int age = Integer.parseInt(age_input);
    if (age >= 18) {
        System.out.println("You can vote!");
    } else {
        System.out.println("Sorry, you can't vote yet.");
    }
} catch (NumberFormatException ex) {
    System.err.println("Invalid input.  '" + age_input + "' is not a valid integer.");
}

这将打印:

输入无效。 ‘abc’不是有效整数。

catch 之后可以添加 finally 子句。无论是否抛出异常,都将始终执行 finally 子句。

try { ... } catch ( ... ) { ... } finally { ... }

String age_input = "abc";
try {
    int age = Integer.parseInt(age_input);
    if (age >= 18) {
        System.out.println("You can vote!");
    } else {
        System.out.println("Sorry, you can't vote yet.");
    }
} catch (NumberFormatException ex) {
    System.err.println("Invalid input.  '" + age_input + "' is not a valid integer.");
} finally {
    System.out.println("This code will always be run, even if an exception is thrown");
}

这将打印:

输入无效。 ‘abc’不是有效整数。
即使抛出异常,也始终会运行此代码