自定义异常
public class MyException extends Exception {
private int errCode;
public MyException() {
}
public MyException(String message, int errCode) {
super(message);
this.errCode = errCode;
}
public int getErrCode() {
return errCode;
}
}
异常测试
public class ExceptionTest {
public static void main(String[] args) {
ExceptionTest exceptionTest = new ExceptionTest();
for (int i = 0; i < 3; i++) {
System.out.println("第" + i + "次循环");
exceptionTest.test1(i);
System.out.println("------------------");
}
}
// 抓住异常
public int test1(int t) {
int i = 0;
try {
test2(t);
i = 1;
System.out.println("try:"+i);
return i;
} catch (MyException e) {
System.out.println("出现异常");
System.out.println("错误代码:"+e.getErrCode()+",错误内容:"+e.getMessage());
i = 2;
System.out.println("catch:"+i);
return i;
} finally {
i = 3;
System.out.println("finally:"+i);
return i;
}
}
// 抛出异常
public void test2(int t) throws Exception{
try {
double result = 10 / t;
} catch (Exception e) {
throw new MyException("分母为0", 100);
}
}
}
输出
第0次循环
出现异常
错误代码:100,错误内容:分母为0
catch:2
finally:3
------------------
第1次循环
try:1
finally:3
------------------
第2次循环
try:1
finally:3
------------------