自定 异常类 MyException
public class MyException extends Exception{
public MyException(){
super();
}
public MyException(String msg){
super(msg);
}
}
测试类 ExceptionTest
public class ExceptionTest{
public static void main(String[] args){
ExceptionTest e = new ExceptionTest();
try{
e.judge();
}
catch(MyException e1){
e1.printStackTrace();
}
}
public void judge() throws MyException{
int age = (int)Math.round(Math.random() * 20+1);
if(age > 18)
throw new MyException(age + "can");
else
System.out.println(age+ " cant");
}
}
<转>
在进行程序开发的过程中,自定义异常遵循以下四个步骤: