一、Demo2.java
package test;
public class Demo2 {
public static void main(String[] args) {
try {
submitOrder(8);
} catch(Exception e) {
System.out.println("我知道库存不足了");
}
}
public static void submitOrder(int stock) {
if(stock > 5) {
//我们主动的抛出异常对象的语法
throw new StockException("库存不足"+stock);
}
System.out.println("购买成功");
}
}
二、StockException.java
package test;
public class StockException extends RuntimeException{
public StockException() {
super();
// TODO Auto-generated constructor stub
}
public StockException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
// TODO Auto-generated constructor stub
}
public StockException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public StockException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public StockException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}
/*继承了父类RuntimeError中的构造器,继承方法
*/