catch代码中的执行语句

catch代码中的执行语句

本文介绍了Java中的try-catch块 - catch代码中的执行语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于Java中catch块中语句执行顺序的问题。
当我运行下面的类Test1(见下文)时,我希望首先输出Hi !,然后是e.printStackTrace()的结果;声明,然后再见!但是,我从来没有得到这个订单。请查看我在下面粘贴的输出。

I have a question about the order of the execution of statements in a catch block in Java.when I run the following class Test1 (see below), I expect to have as output first Hi!, then the result of the e.printStackTrace(); statement, and then Bye!. However, I never get this order. Please, look at the outputs, which I have pasted below.

public class Test1 {

    public static void calculate() {
        try {
             int h = 5/0;
        } catch (ArithmeticException e) {
            System.out.println("Hi!");
            e.printStackTrace();
        }
        System.out.println("Bye!");
    }

    public static void main(String[] args) {
        calculate();
    }

}

输出1:


Hi!
Bye!
java.lang.ArithmeticException: / by zero
    at Test1.calculate(Test1.java:6)
    at Test1.main(Test1.java:15)

输出2:


java.lang.ArithmeticException: / by zero
    at Test1.calculate(Test1.java:6)
    at Test1.main(Test1.java:15)
Hi!
Bye!

我有两个问题:

1。)更重要的问题:为什么我总是嗨!再见!即使代码中的mye.printStackTrace()在它们之间,也总是一个接一个地打印出来?

1.) The more important question: Why I always have Hi! and Bye! printed always one after the other, even though mye.printStackTrace() in the code is between them?

2。)为什么有时我会得到语句e的输出。在Hi!之前的printStackTrace(),有时候在Bye之后! ?我已经多次运行该程序,我无法理解在什么情况下我得到一个或另一个打印。

2.) Why sometimes I have the output of the statement e.printStackTrace() before Hi!, and sometimes after Bye! ? I have run the program many times and I cannot understand under what circumstances I get one or the other print.

谢谢。

我使用的是Java 6和Eclipse(Ganymed)。

I am using Java 6, and Eclipse (Ganymed).

推荐答案

打印到 系统.err 嗨!再见!是在 System.out 。如果您在常规控制台上运行程序,它们最终会出现在屏幕上,但订单可能已经完成。如果您通过IDE运行程序(例如),则流可能会使用颜色编码,以便您可以很容易地区分它们。

Exception.printStackTrace() prints to System.err whereas "Hi!" and "Bye!" are on System.out. If you run your program on a regular console, they eventually end up on the screen, but the order may be out. If you are running the program through an IDE (e.g. NetBeans), the streams will probably be color-coded so you can easily distinguish them.

这篇关于Java中的try-catch块 - catch代码中的执行语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:24