Java 关于异常处理(2)

class Test{
public int devide(int x,int y) throws Exception{
if(y<0) throw new DevideByMinusException("devide is"+y);
return x/y;
}
}

//自定义异常
class DevideByMinusException extends Exception{
DevideByMinusException(String msn){
super(msn);
}
}
public class TestException {

public static void main(String[] args) /*throws Exception*/{
//TODO Auto-generated method stub
try{
new Test().devide(3, -1);   //除数为-1,则Test中抛出 DevideByMinusException异常,被try-catch捕获

}catch(Exception e){
System.out.println(e.getMessage());    //打印出详细异常信息,即刚刚传给异常的构造器的内容
}
System.out.println("Programme is running");
}

}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwpwfx.html