2010-12-11 73 views
2

我想知道怎样的错误可以在java中被捕获,但允许程序继续运行。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"); 
     } 
    } 
} 

打印以下内容:

a 
j 
the index is out of bounds 

但之后引发错误我想代码继续运行,因此,这是印刷:

a 
j 
the index is out of bounds 
is it still running 

在此先感谢

回答

7

Java不支持“恢复”或异常后“重启”。

你可以在try/catch(在上面的例子中总共3个,每个访问一个)包装特定行“跳过”,或者更好的是编写不会抛出异常的代码 - 异常真的应该成为“特殊”的IMOHO。您也可以移动try/catch代码放到一个方法来“包装”的接入(例如,调用该方法3次),但行为是相同的。

+0

这是我希望避免,很好哦,感谢有关Java :) – java 2010-12-11 04:52:30

+0

@java针对特定问题的信息种类-的,它(另)一个问题可能是有益的。另外,对发现SO和大房间的整体吨知识的不同(有时更好)接近给定的问题,一组特定的约束条件(例如,Java)内。 – 2010-12-11 07:02:52

2
for(int i =0; i < Short.MAX_VALUE; i++){ 
try{ 
    System.out.println(str.charAt(i)); 
}catch(Exception ex){} 
} 

如果您希望始终执行,您还可以使用finally bolck。

+0

哈哈。 +1的好泛化。 – 2010-12-11 04:02:20

+0

但我不想永远打印值,除了这将是更好地使I java 2010-12-11 04:51:16

相关问题