异常处理:
①捕获异常
选中代码后ctrl+Alt+t:
try catch捕捉异常
②抛出异常
加上throws 异常类型
自定义异常
Exception.java:
package Exception;
//自定义运行时异常
public class ExceptionTest {
public static void main(String[] args) {
//保存一个合法的年龄
try {
saveAge(160);
System.out.println("底层执行成功");
} catch (Exception e) {
e.printStackTrace();//输出异常信息
System.out.println("底层执行失败");
}
}
public static void saveAge(int age){
if (age < 0 && age < 150) {
System.out.println("年龄被成功保存:"+age);
}else{
//用一个异常对象封装这个问题
//throw抛出这个异常对象
throw new AgeIllegalRunTimrException("age is illegal ,your age is " + age);
}
}
}
AgeIllegalRunTimrException.java:
package Exception;
//必须让这个类继承RuntimeException
public class AgeIllegalRunTimrException extends RuntimeException{
public AgeIllegalRunTimrException(String message) {
super(message);
}
public AgeIllegalRunTimrException() {
}
}
输出:
Exception.AgeIllegalRunTimrException: age is illegal ,your age is 160
at Exception.ExceptionTest.saveAge(ExceptionTest.java:21)
at Exception.ExceptionTest.main(ExceptionTest.java:9)
底层执行失败