- 自定义异常类
- 如果Java提供的异常类型不能满足程序设计的需要,我们可以定义自己的异常类型。
- 用户自定义的异常类应为 Exception 类(或者Exception 类的子类)的子类
示例代码:
package 自定义异常;
/**
* 自定义异常:商品不存在异常
*
* 自定义异常的要求:
* 1、继承Exception
* 2、复写
* <p>Title: ProcutNotExistException</p>
* <p>Description: </p>
* @author xianxian
* @date 2019年7月10日
*/
public class ProductNotExistException extends Exception{
/**
* serialVersionUID
* 关于serialVersionUID讲解比较详细的博客
* https://blog.csdn.net/wuzhong8809/article/details/83416579
* https://blog.csdn.net/u014750606/article/details/80040130
*/
private static final long serialVersionUID = -1046619572695534339L;
//Eclipse: source ---> generate constructors from superclass
/**
* 当要抛出异常时会调用该构造方法,实例化一个异常对象
* <p>Title: </p>
* <p>Description: </p>
* @param message
*/
public ProductNotExistException(String message) {
super(message);
}
}
package 自定义异常;
public class ProductService {
/**
* 查找商品的方法
* @throws ProductNotExistException
*/
public void queryProduct(int id) throws ProductNotExistException {
if(id == 0) {
throw new ProductNotExistException("商品不存在");
}else {
System.out.println("找到商品了");
}
}
}
package 自定义异常;
public class Test {
public static void main(String[] args) {
ProductService service = new ProductService();
try {
service.queryProduct(0);
} catch (ProductNotExistException e) {
e.printStackTrace();
}
}
}
拓展知识点
Java类中serialversionuid 作用 是什么?举个例子说明
以上就是我关于 Java-自定义异常类 知识点的整理与总结的全部内容,另附源码
分割线
博主为咯学编程:父母不同意学编程,现已断绝关系;恋人不同意学编程,现已分手;亲戚不同意学编程,现已断绝来往;老板不同意学编程,现已失业三十年。。。。。。如果此博文有帮到你欢迎打赏,金额不限。。。