`

Java 自定义异常类

    博客分类:
  • Java
 
阅读更多
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 就业培训教程》

  • 大小: 245.7 KB
  • 大小: 83.5 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics