26 自定义异常

案例

设置一个异常:非法年龄异常,当Person类的setAge方法检测到参数age的值大于100或小于0时,抛出该异常。

需要注意的地方

  • 自定义异常继承自Exception或RuntimeException
  • 异常后显示的自定义信息定义在构造方法中,如下面代码
  • 异常要声明在方法后面:方法() throws 自定义异常名
  • 抛出异常的代码为:throw new 自定义异常名("需要显示的错误信息");
  • 对可能出现自定义异常的方法进行trycatch

自定义异常

写一个异常类,继承自Exception或RuntimeException,其中,继承自RuntimeException的异常无需向上声明。

以下的重写方法可以直接右键-》sround-》generate Constructors from superClass-》全选-》确定

package exception;
/**
 * 非法年龄异常
 * @author TEDU
 *
 */
public class IllegalAgeException  extends Exception{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public IllegalAgeException() {
		super();
		// TODO Auto-generated constructor stub
	}

	public IllegalAgeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
		// TODO Auto-generated constructor stub
	}

	public IllegalAgeException(String message, Throwable cause) {
		super(message, cause);
		// TODO Auto-generated constructor stub
	}

	public IllegalAgeException(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}

	public IllegalAgeException(Throwable cause) {
		super(cause);
		// TODO Auto-generated constructor stub
	}

}

  

Person类

在setAge时做处理,当不符合年龄范围则new并抛出异常

package exception;

public class Person {
	int age;

	public int getAge() {
		return age;
	}

	public void setAge(int age) throws IllegalAgeException {//注意这里要抛出
		if(age>100||age<0) {
			throw new IllegalAgeException("年龄非法");//这里要new
		}
		this.age = age;
	}
	
}

  

测试类

当输入:p.setAge()时,由于这个方法抛出了异常,必须处理或向上声明。这里我们直接处理它,用try-catch:

package exception;

public class ThrowDemo {
	public static void main(String[] args) {
		Person p  = new Person();
		try {
			p.setAge(1000);
		} catch (IllegalAgeException e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}
}

  

另外我们可以在catch中使用e.getMessage()获取错误提示信息,如上面的自定义异常,获取到的字符串就是:

"年龄非法"
原文地址:https://www.cnblogs.com/Scorpicat/p/11973145.html