【发布时间】:2020-03-06 15:28:06
【问题描述】:
我们有两个相似的代码,它们都会导致 RunTimeException。但是,其中一个代码将打印出结果+异常,而另一个代码仅在没有结果的情况下抛出异常,直到抛出异常为止。你可以在这里看到这两个代码块,其中一个被注释掉了:
第一种情况:
public class ExceptionTest {
public static void main(String[] args) {
String letters = "abcdef";
System.out.println(letters.length());
System.out.println(letters.charAt(3));
System.out.println(letters.charAt(6));
}
}
第二种情况:
public class ExceptionTest {
public static void main(String[] args) {
int total = 0;
StringBuilder letters = new StringBuilder ("abcdefgh");
total += letters.substring(1, 2).length();
total += letters.substring(6, 6).length();
total += letters.substring(6, 5).length();
System.out.println(total);
}
}
谁能解释为什么它只会打印 RuntimeException 而不会在注释代码块中包含结果?
【问题讨论】:
-
在第一个 sn-p 中,您在每一行中打印一些值。在第二个中,在所有操作完成后,您只尝试对其进行一次打印。其中一项操作会引发异常,因此永远不会到达 print 语句。
标签: java runtimeexception