自定义异常
目录分类
-
检查性异常类:自定义异常类继承于Exception。
-
运行时异常类:自定义异常类继承于
RuntimeException
自定义检查性异常类(MyException)
public class MyException extends Exception {
public MyException() { } // 无参构造
public MyException(String msg) {
super(msg); // msg : 异常提示信息
}
public MyException(Throwable throwable) {
super(throwable);// throwable 类型
}
}
自定义运行时异常类(MyRuntimeException)
public class MyRuntimeException extends RuntimeException {
public MyRuntimeException() { } // 无参构造
public MyRuntimeException(String msg) {
super(msg); // msg : 异常提示信息
}
public MyRuntimeException(Throwable throwable) {
super(throwable);// throwable 类型
}
}
自定义异常的使用实例
public class ExceptionDemo {
public static void main(String[] args) throws Exception {
int i = demo(3);
System.out.println("i = " + i);
}
public static int demo(int index) throws MyException{
int[] arr = {1,2,3};
if(index >= arr.length || index < 0)
throw new MyRuntimeException("您传递的索引错误,数组索引在0-2之间");
return arr[index];
}
}
标签:自定义,MyException,MyRuntimeException,throwable,异常,public
From: https://www.cnblogs.com/luoyiwen123/p/18343341