ITeye博客

Java 自定义异常类

何不笑 · 2013-02-22 10:58 · Java · 编程语言 · Markdown

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 就业培训教程》

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。