简体   繁体   English

抛出运行时异常之前的控制台输出

[英]Console output before runtimeexception is thrown

We have two similar codes which both results in a RunTimeException.我们有两个相似的代码,它们都导致 RunTimeException。 However, one of the codes will print out the results + exception while the other one ONLY throws the exception without the results up until the point the exception is thrown.但是,其中一个代码将打印出结果 + 异常,而另一个代码只抛出异常而没有结果,直到抛出异常为止。 You can see both blocks of code here, one is commented out:你可以在这里看到两个代码块,其中一个被注释掉:

First case:第一种情况:

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));

 }
}

Second case :第二种情况:

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);

 }
}

Can anyone explain why it will print only the RuntimeException and not include the results in the commented code block?谁能解释为什么它只会打印 RuntimeException 而不会在注释的代码块中包含结果?

The output comes from System.out.println().输出来自 System.out.println()。 In the commented out version the Exception is caused by substring(6,5) I think and that comes before the println().在注释掉的版本中,异常是由 substring(6,5) 引起的,我认为它出现在 println() 之前。

    String letters = "abcdef";

    System.out.println(letters.length());
    System.out.println(letters.charAt(3));
    System.out.println(letters.charAt(6)); // <--- fails

This code fails at the commented line, after the execution of System.out.println(letters.length());执行System.out.println(letters.length());后,此代码在注释行失败System.out.println(letters.length()); and System.out.println(letters.charAt(3));System.out.println(letters.charAt(3)); . . So you are able to see the two outputs.所以你可以看到两个输出。

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(); //<-- fails

System.out.println(total);

This code fails before System.out.println(total);此代码在System.out.println(total);之前失败System.out.println(total); , so there is no output ,所以没有输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM