5. 自定义异常
1.1 定义一个类并继承Exception1.2 使用throw关键字,在方法体中抛出异常对象
1.3 使用throws关键字,在方法声明中抛出异常
1.4 实例,高压锅压力太高抛出异常
package com.geek99.demo;
public class Test {
public static void main(String[] args) {
Pan p = new Pan(400);
try {
p.use();
} catch (PanExp e) {
e.printStackTrace();
}
}
}
class PanExp extends Exception{
int p;
public PanExp(int p,String name){
super(name);
this.p = p;
}
}
class Pan{
int p;
public Pan(int p){
this.p = p;
}
public void use()throws PanExp{
if(p>500){
throw new PanExp(p,"压力太高,危险!");
}
System.out.println("正常运行...");
}
}
原文出处:http://geek99.com/node/443#
该博客教程视频地址:http://geek99.com/node/1639
转载于:https://blog.51cto.com/8785849/1413384