4.7-4.9学习总结
目录
异常处理
1.必要性
2.异常分类
3.异常类的继承体系
4.异常处理方式
1.try-catch-finally
2.throws +异常列表
5.自定义异常
6.throw与throws
异常处理
1.必要性
- 人的考虑有限,异常情况总比考虑到的要多
- 异常处理代码和正常业务代码分离,代码更加优雅,程序更加健壮(不会因为一个异常而导致整个程序崩溃)
2.异常分类
语法错误和逻辑错误不是异常
包括
- Error:JVM无法解决的严重问题
- Exception:其他因编程错误或偶然因素导致的一般性问题,可用针对性代码处理。包括Checked编译异常和Runtime运行异常。编译异常必须显示处理
3.异常类的继承体系
ArithmeticException 数学运算异常
ClassCastException 类型转化异常
NumberFormatException数字格式不正确异常
4.异常处理方式
1.try-catch-finally
try{//可能出现异常的代码//若出现异常,不执行异常发生后的代码
}catch(Exception e){//捕获异常,将异常封装为Exception对象e,传给catch//在这里处理异常//没有捕获到异常不执行catch
}fianlly{//无论有没有捕获到异常,finally始终会执行//可用于释放资源,关闭连接
}
当try中有多个异常时,可用多个catch分别捕获不同的异常, 注意子类异常要放在父类前面。多个catch只有一个catch会捕获到异常
public class exception {public static void main(String[] args) {int x=1;int y=0;int[] arr={0,1,2,3,4};Person p=null;try{p.temp();System.out.println(x/y);System.out.println(arr[8]);}catch (ArithmeticException e){System.out.println(e.getMessage());}catch (NullPointerException e){System.out.println(e.getMessage());}catch (ArrayIndexOutOfBoundsException e){System.out.println(e.getMessage());//}}
}
class Person{void temp(){System.out.println(666);}
}
try-finally 不捕获异常,发生异常时,先执行finally,再崩程序。
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner sc=new Scanner(System.in);int n;String s;while(true){try{System.out.println("请输入一个整数");s=sc.next();n=Integer.parseInt(s);break;}catch (NumberFormatException e){System.out.println("请重新输入");}}}
}
2.throws +异常列表
将异常抛出,交给调用者处理,最顶级的处理者为JVM
- JVM处理时,直接退出程序
- 没有显式处理异常时,默认throws
- 编译异常需要显式throws
- 规定子类重写父类方法时,抛出异常类型要么一致,要么为父类异常的子类
5.自定义异常
自定义异常类名 继承Exception或RuntimeException
若继承Exception属于编译异常,需要显示处理
若继承RuntimeException 属于运行异常
public class Main {public static void main(String[] args) {Scanner sc=new Scanner(System.in);int n;String s;int age=200;try {if(!(age>=0&&age<=120)){throw new AgeException("年龄小于0或者大于120");}} catch (Exception e) {System.out.println(e.getMessage());}
}
class AgeException extends RuntimeException{public AgeException(String massage){super(massage);}
}
6.throw与throws
throws是异常处理的一种方式,位于方法声明处,后跟异常列表
throw是用于手动生成异常对象的关键字,位于方法体中,后跟异常对象