11.9 自定义异常
demo
- 在项目开发中,会大量接触自定义异常
- 本节案例,综合本章节很多案例。
class BombException extends Exception {// 自定义强制处理异常
public BombException(String msg){
super(msg);// 调用父类构造
}
}
class Food {
public static void eat(int num) throws BombException {
if(num > 9){
throw new BombException("米饭吃太多了,肚子爆炸了");
} else {
System.out.println("正常吃");
}
}
}
public class JavaDemo {
public static void main(String args[]) {
try {
Food.eat(11);// 传入吃几碗米饭
} catch (BombException e){
e.printStackTrace();
}
}
}
相信坚持的力量,日复一日的习惯.