public class ExceptionTest {
public static void main(String [] args){
int result;
Test test = new Test();
try{
//result = test.devide(10, 0);
result = test.devide(10, -2);
//result = test.devide(10, 2);
}catch (DevidedByMinusException e) {
System.out.println(e.getMessage()+"; the devisor is "+e.getDevisor());
}catch (ArithmeticException e) {
System.out.println(e.getMessage());
}catch (Exception e) {
System.out.println(e.getMessage());
}finally{
System.out.println("finally");
}
System.out.println("The program is running here, that is normal!");
}
}
class DevidedByMinusException extends Exception{
int devisor;
public DevidedByMinusException(String msg, int divisor){
super(msg);
this.devisor = devisor;
}
public int getDevisor() {
return devisor;
}
}
class Test{
public int devide(int x, int y) throws ArithmeticException, DevidedByMinusException{
if(y < 0){
throw new DevidedByMinusException("被除数为负", y);
}
return x/y;
}
}
选自《Java 就业培训教程》