java 自定义异常
?
java 语言针对常见异常状况已事先定义了相应的导常类型,并在程序运行出错时由系统自动创建相应异常对象并进行抛出、捕获和处理,当然我们也可以自己定义新的异常类型并人工抛出异常对象
?
自己定义的类
?
@SuppressWarnings("serial")public class MyException extends Exception {private int exceptionType;public MyException(String message, int exceptionType) {super(message);this.exceptionType = exceptionType;}public int getExceptionType() {return exceptionType;}}
?
?
测试类如下
?
public class TestMyException {public int testNum(int age) throws MyException {if (age >= 100 || age <= 0) {throw new MyException(" age is: " + age + " age is between 0 and 100", 4);} else {return age;}}public static void main(String[] args) {TestMyException my = new TestMyException();try {my.testNum(123);} catch (MyException e) {System.out.println(e.getMessage() + " " + e.getExceptionType());}}}
?
运行结果如下
?
age is: 123 age is between 0 and 100 4
?
?