frankyara 2017-01-01 16:28 采纳率: 0%
浏览 958
已采纳

why only catch the first Exception of f(0)

// exceptions/Ex9.java
// TIJ4 Chapter Exceptions, Exercise 9, page 460
/* Create three new types of exceptions. Write a class with a method that

  • throws all three. In main(), call the method but only use a single catch
  • clause that will catch all three types of exceptions. / //import static net.mindview.util.Print.;

class ExceptionA extends Exception {
ExceptionA(String msg) { super(msg); }

}

class ExceptionB extends Exception {
ExceptionB(String msg) { super(msg); }

}

class ExceptionC extends Exception {
ExceptionC(String msg) { super(msg); }

}

public class Ex9 {
public static void f(int x) throws ExceptionA, ExceptionB, ExceptionC {
if(x < 0) throw new ExceptionA("x < 0");
if(x == 0) throw new ExceptionB("x == 0");
if(x > 0) throw new ExceptionC("x > 0");
}
public static void main(String[] args) {
try {
f(0);
f(1);
f(-1);
// will catch any Exception type:
} catch(Exception e) {
System.out.println("Caught Exception");
e.printStackTrace(System.out);
}
}

}

  • 写回答

1条回答 默认 最新

  • frankyara 2017-01-01 16:30
    关注

    i think of it.doing like this

    try {
            f(0);
        } catch (ExceptionA | ExceptionB | ExceptionC e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            f(1);
        } catch (ExceptionA | ExceptionB | ExceptionC e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            f(-1);
        } catch (ExceptionA | ExceptionB | ExceptionC e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器