java - 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();
}
}
解决方案
您的两个问题是您有多个 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");
}
推荐阅读
- python - 如何在并行映射中传递“常量”参数?
- amazon-web-services - Cognito 通过 AWS lambda 函数授权用户
- python - 计算 Jacobian x Jacobian.T 的有效方法
- shell - 如何将剪贴板内容从/粘贴到 IBM Cloud Shell?
- node.js - NestJs 和 Jest:等待请求抛出 404
- sql - SQL Lag 函数和 where 子句
- node.js - sequelize 获取引用表的列值
- jmeter - 在 ISO8583 的 JMeter 上使用 JPOS 运行多个线程时出错
- c - 查找哪个分隔符导致在 C 中 strtok() 处的索引值处拆分
- python - 将子字符串替换为
子串 在美丽汤