有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

重新触发异常时调用序列中的java差异

考虑以下方法:A:()调用B(),这又调用C.()p>

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()打印完整的stacktrace之前,包含在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)

既然这是单线程的,为什么在多个运行中行为会发生变化


共 (1) 个答案