gpt4 book ai didi

java - 在程序完成之前出现异常详细信息?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:53:37 27 4
gpt4 key购买 nike

我有一个 for 循环:

for(Location l : locs) {
System.out.println("X:"+l.getX()+", Y:"+l.getY());
try {
if(layer.getObject(l) != null)
out.add(layer.getObject(l));

} catch(NullPointerException e) {

}
}

每次迭代,它从 Location[] 数组中获取一个 Location,并打印出该位置的 X 和 Y。然后,下一行从 map 层(不是标准 map 库)中的位置获取对象,并将其添加到 ArrayList

我得到一个 java.lang.ClassCastException,但这不是我的问题。这个问题我可以自己解决。我的问题是为什么输出看起来像这样(特别是异常显示的方式):

run:
X:0, Y:1
X:0, Y:2
X:0, Y:3
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LMapGrid.OverlayObject;
X:1, Y:1
X:1, Y:3
X:2, Y:1
X:2, Y:2
X:2, Y:3
at MapGrid.MapGrid.getAdjacentOfType(MapGrid.java:86)
at BehaviorMap.BehaviorMap.main(BehaviorMap.java:26)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

它找到的对象位于位置 (1,1),因此,异常在位置 (1,1) 处抛出。这是从程序一开始就设置的。该程序在主线程上运行。不过,我的问题是为什么输出会这样显示?

这种布局方式似乎暗示异常是在程序到达 (0,3) 时抛出的,但异常一定是在到达 (1,1) 时抛出的。然后,输出将暗示,一旦发现异常,程序将继续执行,直到循环退出。

我不明白这种行为。当遇到未处理的异常时,为什么程序不直接退出呢?此外,为什么异常消息出现在调用异常的行之前?请注意,System.out.println 出现在 try block 之前。

最后,为什么错误以如此奇怪的方式 split ? (在那个报错信息出现,然后在程序出现继续执行后出现详细信息。)平台是NetBeans 7.2。

最佳答案

The way this is laid out would seem to imply that the Exception was thrown when the program reached (0,3), but the exception must have been thrown when it reached (1,1). Then, the output would imply that, once the exception was found, the program continued to execute until the loop exited.

未捕获异常的默认行为是将它们打印到标准错误流 (System.err)。这可以以与标准输出流 (System.out) 不同的顺序显示在控制台上。

I don't understand this behavior. When an unhandled exception is encountered, why doesn't the program simply exit? Additionally, why does the Exception message appear before the line invoking the Exception? Note that the System.out.println comes before the try block.

这取决于 MapGrid.MapGrid.getAdjacentOfType 正在做什么。看起来它正在捕获异常并调用 Exception.printStackTrace(),这会打印到标准错误。

Lastly, why does the error split in such an odd way? Being that the error message appears, then the details appear after the program appears to continue execution. Platform is NetBeans 7.2.

同样,因为输出和错误流不一定按照它们写入的相同顺序(相对于彼此)显示在控制台上。

关于java - 在程序完成之前出现异常详细信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14888927/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com