java中如何一次拋出多個異常?
百度搜索圈T社區 免費行業視頻教程
www.aiquanti.com
基本思路就是定義三個類,繼承異常的父類,然后在需要拋出異常的地方,throws一下就可以了,示例如下:
public class CatchMultiException {
public static void main(String[] args) throws Exception {
try {
test(2);
} catch (Exception e) {
if (e instanceof TestAException || e instanceof TestBException
e instanceof TestCException) {
e.printStackTrace();
} else {
throw e;
}
}
}
public static void test(int a) throws TestAException, TestBException,
TestCException {
if (a == 0) {
throw new TestAException();//拋出第一個異常
}
if (a == 1) {
throw new TestBException();//拋出第二個異常
}
if (a == 2) {
throw new TestCException();//拋出第三個異常
}
}
}
class TestAException extends Exception {//繼承父類Exception
private static final long serialVersionUID = 1L;
}
class TestBException extends Exception {
private static final long serialVersionUID = 1L;
}
class TestCException extends Exception {
private static final long serialVersionUID = 1L;
}