Java异常处理 - 意外输出

时间:2015-10-05 07:53:12

标签: java exception

我有以下Java代码 - 初学者指南(Schildt),第9章。

package com.chapter.nine;

public class UseThrowableMethods {

    public static void main(String args[]){
        try {
            ExcTest.genException();
        }
        catch (ArrayIndexOutOfBoundsException excp){
            System.out.println("Standard message is:");
            System.out.println(excp);
            System.out.println("\nStack Trace:");
            excp.printStackTrace();
        }

        System.out.println("After the catch statement");
    }
}


public class ExcTest {
    static void genException(){ 
        int nums[] = new int [4];
        System.out.println("Before an exception is generated");
        nums[7] = 10;
        System.out.println("This should not be displayed");
    }
}

问题在于我希望控制台上显示的输出与Book(以及Debug Session中)相同,即:

Before an exception is generated
Standard message is:
java.lang.ArrayIndexOutOfBoundsException: 7

Stack Trace:
java.lang.ArrayIndexOutOfBoundsException: 7
    at com.chapter.nine.ExcTest.genException(ExcTest.java:11)
    at com.chapter.nine.UseThrowableMethods.main(UseThrowableMethods.java:12)
After the catch statement

但是,当我运行代码时,显示的实际输出如下:

com.chapter.nine.UseThrowableMethods
Before an exception is generated
java.lang.ArrayIndexOutOfBoundsException: 7
Standard message is:
    at com.chapter.nine.ExcTest.genException(ExcTest.java:11)
java.lang.ArrayIndexOutOfBoundsException: 7

    at com.chapter.nine.UseThrowableMethods.main(UseThrowableMethods.java:12)
Stack Trace:
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
After the catch statement
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

Process finished with exit code 0

发生了什么事?

0 个答案:

没有答案