运行时异常
package Exception;
public class ExceptionTest1 {
public static void main(String[] args) {
try {
saveAge(230);
System.out.println("底层运行成功");
} catch (Exception e) {
e.printStackTrace();
System.out.println("底层运行失败");
}
}
public static void saveAge(int age){
if(age>=0&&age<=120){
System.out.println("年龄保存成功");
}else{
//throw抛出这个异常对象
throw new AgeIllegalRunTimeException("age is illegal,your age is "+age);
}
}
}
package Exception;
public class AgeIllegalRunTimeException extends RuntimeException {
public AgeIllegalRunTimeException() {
}
public AgeIllegalRunTimeException(String message) {
super(message);
}
}
编译时异常
package Exception;
public class ExceptionTest2 {
public static void main(String[] args) {
try {
saveAge1(23);
System.out.println("底层运行成功");
} catch (Exception e) {
e.printStackTrace();
System.out.println("底层运行失败");
}
}
public static void saveAge1(int age) throws AgeIllegalException{
if(age>=0&&age<=120){
System.out.println("年龄保存成功");
}else{
//throw抛出这个异常对象
//throws用在方法上,抛出方法内部的异常
throw new AgeIllegalException("age is illegal,your age is "+age);
}
}
}
package Exception;
public class AgeIllegalException extends Exception{
public AgeIllegalException() {
}
public AgeIllegalException(String message) {
super(message);
}
}
异常的处理