一,认识异常
1,异常就是代表程序出现的问题
2,两类异常
运行时异常:RuntimeException及其子类,编译阶段不会出现错误提示,运行时出现的异常
编译时异常:编译阶段就会出现错误提示
二,自定义异常
1.Java无法为世界上全部问题提供异常来代表
2,自定义异常的种类
自定义运行时异常
1.定义一个异常类继承RuntimeException
2.重写构造器
3.通过throw new异常类(xxx)来创造异常对象并抛出
编译阶段不报错,提醒不强烈,运行时才可能出现
public class AgeIllegalRuntimeException extends RuntimeException{ public AgeIllegalRuntimeException() { } public AgeIllegalRuntimeException(String message) { super(message); } }
public static void saveAge(int age){ if (age>0&&age<150){ System.out.println("年龄被成功保存:"+age); }else { throw new AgeIllegalRuntimeException("/age is illegal,your age is"+age); } }
//需求:保存一个合法的年龄
try {
saveAge(16);
System.out.println("底层执行成功的!");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//出现异常,可以用throw,也可以用try-catch
自定义编译时异常
1.定义一个异常类继承Exception
2.重写构造器
3. 通过throw new异常类(xxx)来创造异常对象并抛出
编译阶段不报错,提醒不强烈,运行时才可能出现
public class AgeIllegalException extends Exception{ public AgeIllegalException() { } public AgeIllegalException(String message) { super(message); } }
public static void saveAge2(int age)throws AgeIllegalException{ if (age>0&&age<150){ System.out.println("年龄被成功保存:"+age); }else { //用一个异常对象封装这个问题 //throw抛出去这个异常对象 //throws用在方法上,抛出方法内部的异常 throw new AgeIllegalException("/age is illegal,your age is"+age); } }
三,异常的处理
1.捕获异常,记录异常并响应合适的信息给用户
//方法中抛出异常,再用try-catch来捕捉异常
2.捕获异常,尝试重新修复
public class ExceptionTest4 {
public static void main(String[] args) {
while (true) {
try {
System.out.println(getMoney());
break;
} catch (Exception e) {
System.out.println("你输入的格式不合法!");
}
}
}
public static double getMoney(){
Scanner sc=new Scanner(System.in);
while (true) {
System.out.println("请您输入金额:");
double money=sc.nextDouble();
if (money>=0){
System.out.println("您输入的金额正确");
return money;
}else{
System.out.println("您输入的金额格式不正确!");
}
}
}
}