编写一个自定义的异常类MyTestException,在另一个程序中使用它

来源:百度知道 编辑:UC知道 时间:2024/06/18 04:59:15

public class TestException {
public static void main(String[] args) {

int i = 0, j = 0;
TestException te = new TestException();
try {
int sum = te.add(i, j);
} catch (MyException e) {
e.printStackTrace();
}
}

// 抛出自定义异常的方法
public int add(int i, int j) throws MyException {
if (i == 0 && j == 0) {
throw new MyException("两个数不能同时为零");
}
return i + j;
}
}

/**
* 自定义的异常类
*/
class MyException extends Exception {
public MyException(String msg) {
super(msg);
}
}