自定义异常和Unhandled exception type Exception

class Person {
    public Person() {
        
    }
    int age;
    public void setAge(int age) throws AgeOutOfBoundException  {    //正常code
        if (age>=0) {
            this.age = age;    
        }
        else {
            throw new AgeOutOfBoundException(age);
        }
    }
    
}
class AgeOutOfBoundException extends Exception {
    public AgeOutOfBoundException(int age) {
        // TODO Auto-generated constructor stub
        super(String.valueOf(age));
    }
}

 编译报错code

class Person {
    public Person() {
        
    }
    int age;
    public void setAge(int age) {    //异常code
        if (age>=0) {
            this.age = age;    
        }
        else {
            throw new AgeOutOfBoundException(age);
        }
    }
    
}
class AgeOutOfBoundException extends Exception {
    public AgeOutOfBoundException(int age) {
        // TODO Auto-generated constructor stub
        super(String.valueOf(age));
    }
}

 原因:

在某个方法中,假如使用了throwable类,必须得对部分代码做try catch或者声明这一段会发生异常。
所以必须添加throw ...Exception.

重点来了:

为什么我在定义方法的时候需要加呢?我可不可以不加throw ....Exception?

答案是可以的。

原因如下,class AgeOutOfBoundException extends Exception 继承的是Exception类,Exception又包含两种,一种是RuntimeException,另一种是剩下的编译报错Exception。

假如继承了Exception,就会提示编译报错,那么继承RuntimeException就可以了。

是的确实如此:

class Person {
	public Person() {
		
	}
	int age;
	public void setAge(int age)  {
		if (age>=0) {
			this.age = age;	
		}
		else {
			throw new AgeOutOfBoundException(age);
		}
	}
	
}
class AgeOutOfBoundException extends RuntimeException {   //继承RuntimeException,而非Exception
	public AgeOutOfBoundException(int age) {
		// TODO Auto-generated constructor stub
		super(String.valueOf(age));
	}
}

 

posted @ 2020-07-22 15:34  游泳的花生人-ATC  阅读(1316)  评论(0编辑  收藏  举报