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));
}
}
