首页 > 解决方案 > java中的多个异常

问题描述

随机有 3 种不同类型的输出。有人可以解释为什么输出是这些吗?

Out1 => "m1_1 m1_3 m1_4 m2_1 m2_3 m3_1 m3_3" 案例例外 3。

Out2 =>“m1_1 m2_2 m2_3 m3_1 m3_3”案例异常2。

Out3 =>“m1_1 m3_2 m3_3”案例异常1。

课程:

class Exception1 extends Exception {
}

class Exception2 extends Exception {
}

class Exception3 extends Exception {
}

public class C {

  public void method1() throws Exception1, Exception2 {
    try {
        System.out.println(Math.random()+"\n");
        System.out.println("m1_1");
        //some code here that will randomly throw Exception1,2,or3
        if (Math.random() <= 0.3) {
            throw new Exception1();
        }
        if (Math.random() < 0.6) {
            throw new Exception2();
        }
        if (Math.random() < 0.9) {
            throw new Exception3();
        }
        System.out.println("m1_2");
    } catch (Exception3 e3) {
        System.out.println("m1_3");
    }
    System.out.println("m1_4");
  }

  public void method2() throws Exception1 {
    try {
        method1();
        System.out.println("m2_1");
    } catch (Exception2 e2) {

        System.out.println("m2_2");
    }
    System.out.println("m2_3");
  }

  public void method3() {
    try {
        method2();
        System.out.println("m3_1");
    } catch (Exception1 e1) {

        System.out.println("m3_2");
    }
    System.out.println("m3_3");
  }
}

类测试者{

public static void main(String[] a) {
    C c = new C();
    c.method3();
}

}

标签: javaexception

解决方案


您的两个问题是您有多个 Math.random 调用,以及符合一个条件的多个 if。

您需要从 Math.random() 获取 1 个数字并使用它,例如:

double rand = Math.random();

然后,您需要将重叠的 if 切换为 else if,因为如果 rand 为 0.1,它将适合所有 3 个 if 条件。

所以最后 method1 应该是这样的:

public void method1() throws Exception1, Exception2 {
    try {
        double rand = Math.random();
        System.out.println(rand+"\n");
        System.out.println("m1_1");
        //some code here that will randomly throw Exception1,2,or3
        if (rand <= 0.3) {
            throw new Exception1();
        }
        else if (rand < 0.6) {
            throw new Exception2();
        }
        else if (rand < 0.9) {
            throw new Exception3();
        }
        System.out.println("m1_2");
    } catch (Exception3 e3) {
        System.out.println("m1_3");
    }
    System.out.println("m1_4");
}

推荐阅读