程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程解疑 >> java-why only catch the first Exception of f(0)

java-why only catch the first Exception of f(0)

編輯:編程解疑
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);
}
}

}

最佳回答:


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();
    }
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved