Java是否支持在异常后恢复程序执行?

jav*_*ava 2 java exception-handling

我想知道如何在java中捕获错误但允许程序继续运行.

这是我的例子:

public class test1 {
    public static void main(String[] args) {
        String str = new String("abcdefghij");
        try {
            System.out.println(str.charAt(0));
            System.out.println(str.charAt(9));
            System.out.println(str.charAt(10));
            System.out.println("is it still running");
        } catch (Exception e) {
            System.out.println("the index is out of bounds");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

打印如下:

a
j
the index is out of bounds
Run Code Online (Sandbox Code Playgroud)

但是在抛出错误之后我希望代码继续运行以便打印出来:

a
j
the index is out of bounds
is it still running
Run Code Online (Sandbox Code Playgroud)

提前致谢

小智 7

Java在异常后不支持"恢复"或"重新启动".

您可以将特定行"跳过"包装在一个try/catch(在上面的示例中将是3个,每个访问一个),或者更好的是,编写不会抛出异常的代码 - 异常真的应该是"特殊的" IMOHO.您还可以将try/catch代码移动到"包装"访问的方法(例如,调用方法3x),但操作是相同的.