如何自定义异常类?

  1. 继承于现有的异常结构: RuntimeException, Exception
  2. 提供全局常量: serialVersionUID
  3. 提供重载的构造器

throw 和 throws 区别:
throw 表示抛出一个异常类的对象,生成异常对象的过程。声明在方法体内。
throws 属于异常处理的一种方式,声明在方法的声明处。

MyException.java

package com.klvchen.java2;

public class MyException extends RuntimeException {
	
	static final long serialVersionUID = -7034897190745766999L;
	
	public MyException() {}
	
	public MyException(String msg) {
		super(msg);
	}

}

StudentTest.java

package com.klvchen.java2;

public class StudentTest {
	public static void main(String[] args) {
		Student s = new Student();
		try {
			s.regist(-100);
		} catch (Exception e) {
//			e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}
	
}


class Student{
	
	private int id;
	
	public void regist(int id) throws Exception{
		if(id > 0) {
			this.id = id;
		}else {
			throw new MyException("不能输入负数");
		}
	}
	
	public String toString() {
		return "Student [;
	}
}

Java 基础(自定义异常)

相关文章:

  • 2022-01-01
  • 2021-12-24
  • 2022-02-23
  • 2021-12-16
猜你喜欢
  • 2021-07-21
  • 2021-06-13
  • 2022-02-10
  • 2022-01-03
  • 2022-12-23
  • 2021-06-22
  • 2021-10-24
相关资源
相似解决方案