自定义异常
1.继承现有的异常结构,RuntimeException,Exception
2.提供全局常量:serialVersionUID
3.提供重载的构造器
自定义异常类
public class MyException extends Exception{ static final long serialVersionUID = -3387512393124229948L; public MyException(){ super(); } public MyException(String msg){ super(msg); } }
测试类
public class ExceptionTest { public static void main(String[] args) { try { method(-10); } catch (MyException e) { e.printStackTrace();//MyException: 负数异常 } } public static void method(int num) throws MyException{ if(num>0){ System.out.println(num); }else{ throw new MyException("负数异常"); } } }