Java自定义异常,应该继承Exception还是Runtime Exception,为什么
2个回答
展开全部
runtimeException是Exception的一个子类型,自定义异常可以继承Exception或其子类.
通常调用一下父类的构造方法。
public class MyException extends Exception {
public MyException() { super(); }
public MyException(String msg) { super(msg); }
public MyException(Throwable cause) { super(cause); }
public MyException(String msg, Throwable cause) { super(msg, cause); }
}
public String[] createArray(int length) throws MyException {
if (length < 0) {
throw new MyException("数组长度小于0,不合法");
}
return new String[length];
}
上面这个例子,你继承RuntimeException也是没问题的.通常继承Exception,范围更大.
通常调用一下父类的构造方法。
public class MyException extends Exception {
public MyException() { super(); }
public MyException(String msg) { super(msg); }
public MyException(Throwable cause) { super(cause); }
public MyException(String msg, Throwable cause) { super(msg, cause); }
}
public String[] createArray(int length) throws MyException {
if (length < 0) {
throw new MyException("数组长度小于0,不合法");
}
return new String[length];
}
上面这个例子,你继承RuntimeException也是没问题的.通常继承Exception,范围更大.
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询