在完成某一功能时,我们经常会想让程序能够处理某些特定的异常,来增强程序的健壮性。然而JDK中定义的异常类是有限的,因此对于某些特定的异常,我们要通过自定义异常的方式将其捕获。
首先,所有的自定义异常都继承了Exception类
自定义Exception只需要实现构造器方法
public class AttributesNumException extends Exception {
public AttributesNumException(String s) {
super(s);
}
}
其他的方法在Exception中都有定义
之后在使用异常时在函数外用throws,函数内用throw,
throws后跟类,throw后跟实例。
例
public void readStellar(File f, CircularOrbit<Stellar, Planet> orbit) throws IOException ,AttributesNumException
{
……
if(parameters.length!=3)
{
throw new AttributesNumException(