Implement a custom exception class inherits only Exception (mandatory exception handling) or a RuntimeException (selective exception handling) to the parent
Example: Implementing custom exception
package cn.mldn.demo;
class BombException extends Exception { // 自定义强制处理异常
public BombException(String msg) {
super(msg); // 调用父类构造
}
}
class Food {
public static void eat(int num) throws BombException {// 吃饭有可能会吃炸肚子
if (num > 9999) {// 吃了多碗米饭
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();
}
}
}
The results of
normal start to eat, afraid of Chi Pang