一,自定义异常类
package test;
public class MyException extends Exception{
/**
* 自定义异常类可以继承Exception或Throwable
*/
private static final long serialVersionUID = 1L;
public MyException(){
super();
}
public MyException(String msg){
super(msg);
}
public MyException(Throwable cause){
super(cause);
}
public MyException(String msg,Throwable cause){
super(msg,cause);
}
}
二,异常类的使用
package test;
public class TestMyException {
public static void method()throws MyException{
throw new MyException("method throw MyException");
}
public static void main(String[] args){
try{
TestMyException.method();
}catch(MyException e){
System.out.println("Exception:"+e.getMessage());
e.printStackTrace();
}finally{
//
}
}
}
运行结果:
Exception:method throw MyException
test.MyException: method throw MyException
at test.TestMyException.method(TestMyException.java:5)
at test.TestMyException.main(TestMyException.java:9)