什么是异常?
异常就是代表程序出现的问题。
异常体系
Error:代表的系统级别错误(属于严重问题),也就是说系统一旦出现问题,sun公司会把这些问题封装成Error对象给出来, 说白了,Error是给sun公司自己用的,不是给我们程序员用的,因此我们开发人员不用管它。
Exception:叫异常,它代表的才是我们程序可能出现的问题,所以,我们程序员通常会用Exception以及它的孩子来封装程序出现的问题。
运行时异常:RuntimeException及其子类,编译阶段不会出现错误提醒,运行时出现的异常(如:数组索引越界异常)
编译时异常:编译阶段就会出现错误提醒的。(如:日期解析异常)
抛出异常
- 在方法上使用throws关键字,可以将方法内部出现的异常抛出去给调用者处理。
捕获异常(try…catch)
- 直接捕获程序出现的异常。
自定义异常
- Java无法为这个世界上全部的问题都提供异常类来代表, 如果企业自己的某种问题,想通过异常来表示,以便用异常来管理该问题,那就需要自己来定义异常类了。
自定义异常的种类
自定义运行时异常
- 定义一个异常类继承RuntimeException
- 重写构造器
- 通过throw new 异常类(xxx)来创建异常对象并抛出。编译阶段不报错,提醒不强烈,运行时才可能出现。
自定义编译时异常
- 定义一个异常类继承Exception
- 重写构造器
- 通过throw new 异常类(xxx)来创建异常对象并抛出。编译阶段就会报错,提醒更加强烈。
异常有什么作用?
- 异常是用来查询系统Bug的关键参考信息
- 异常可以作为方法内部的一种特殊返回值,以便通知上层调用者底层的执行情况。
public static void main(String[] args) {
try {
saveAge(180);
System.out.println("运行成功");
} catch (Exception e) {
System.out.println("底层出现了问题");
throw new RuntimeException(e);
}
try {
saveAge2(20);
System.out.println("");
} catch (AgeIllegaleException e) {
throw new RuntimeException(e);
}
}
public static void saveAge(int age){
if(age>0&&age<150){
System.out.println("您的年龄被保存成功:"+age);
}else{
//用一个异常对象封装这个问题
//throw 抛出异常对象
throw new AgeRunTimeIllegale("/age is illagle,your age is"+age);
}
}
public static void saveAge2(int age)throws AgeIllegaleException {
if(age>0&&age<150){
System.out.println("您的年龄被保存成功:"+age);
}else{
//用一个异常对象封装这个问题
//throw 抛出异常对象
//throws 用在方法上,抛出内部的异常
throw new AgeIllegaleException("/age is illagle,your age is"+age);
}
}
public class AgeIllegaleException extends Exception{
public AgeIllegaleException() {
}
public AgeIllegaleException(String message) {
super(message);
}
}
public class AgeRunTimeIllegale extends RuntimeException{
public AgeRunTimeIllegale() {
}
public AgeRunTimeIllegale(String message) {
super(message);
}
}
异常处理
抛出异常
建议不用写错误的名称,直接写Exception就可以了。
捕获异常(try…catch)
Exception可以代表捕获一切异常