java - 重新抛出异常时调用顺序的差异

标签 java exception

考虑以下带有方法的类:a() 调用 b(),b() 又调用 c()。

public class ReThrower {

    public static void a(int a1){
        try{
           a1+=1;
           b(a1);
        }
        catch(ArithmeticException e){
            System.out.println("Exception caught at a");
            throw e;
        }
    }

    public static void b(int b1){
        try{
            b1+=1;
            c(b1);
        }
        catch(ArithmeticException e){
            System.out.println("Exception caught at b");
            throw e;
        }

    }

    public static void c(int c1){
        int zero=0,result;
        try{
            result=c1/zero;
        }
        catch(ArithmeticException e){
            System.out.println("Exception caught at c");
            e.printStackTrace();
            throw e;
        }

    }

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

}

当我运行上面的代码时,收到的初始输出是:

Exception caught at c
java.lang.ArithmeticException: / by zero
Exception caught at b
Exception caught at a
    at com.atul.security.ReThrower.c(ReThrower.java:31)
    at com.atul.security.ReThrower.b(ReThrower.java:20)
    at com.atul.security.ReThrower.a(ReThrower.java:10)
    at com.atul.security.ReThrower.main(ReThrower.java:46)
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at com.atul.security.ReThrower.c(ReThrower.java:31)
    at com.atul.security.ReThrower.b(ReThrower.java:20)
    at com.atul.security.ReThrower.a(ReThrower.java:10)
    at com.atul.security.ReThrower.main(ReThrower.java:46)

甚至在 c() 打印完整堆栈跟踪之前,b() 和 a() 中包含的 sysout 已经执行。 然而,当我再次运行它时,输出发生了这样的变化:

    Exception caught at c
Exception caught at b
Exception caught at a
java.lang.ArithmeticException: / by zero
    at com.atul.security.ReThrower.c(ReThrower.java:31)
    at com.atul.security.ReThrower.b(ReThrower.java:20)
    at com.atul.security.ReThrower.a(ReThrower.java:10)
    at com.atul.security.ReThrower.main(ReThrower.java:46)
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at com.atul.security.ReThrower.c(ReThrower.java:31)
    at com.atul.security.ReThrower.b(ReThrower.java:20)
    at com.atul.security.ReThrower.a(ReThrower.java:10)
    at com.atul.security.ReThrower.main(ReThrower.java:46)

鉴于这是单线程的,为什么在多次运行时行为会发生变化?

最佳答案

e.printStacktrace 打印到 System.err,而您使用 System.out 打印其余行。当您打印到两个流时 the result can look out of order .

关于java - 重新抛出异常时调用顺序的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17167541/

相关文章:

java - t :datatable apply css on row

java - NoSuchFieldError : INCLUDE_ALL (Web Service)

java - 使用子类化替换未实现接口(interface)的 Java 类

java - 如何在Android中检查EditText字段在运行时是否有更改内容

java.util.Collections 上的 Java 泛型警告

Java如何防止空对象异常

javascript - Firefox 中的 NS_ERROR_INVALID_POINTER 错误是什么?

java - 异常没有 "cause"参数

python - 在 python 的自定义错误类中调用 super 有什么意义?

c++ - 无法看到导致核心转储终止的异常