自定義異常和Unhandled exception type Exception
阿新 • • 發佈:2020-07-22
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.