异常的概念与体系结构
异常的概念
在java中,将程序执行过程中发生的不正常行为称为异常。如我们经常遇到的:
- 算术异常
public class Test {
public static void main(String[] args) {
System.out.println(10 / 0);
}
}
//执行结果:
//Exception in thread "main" java.lang.ArithmeticException: / by zero
- 数组越界异常
public class Test {
public static void main(String[] args) {
int[] array = new int[]{1,2,3};
System.out.println(array[100]);
}
}
//执行结果:
//Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 100 out of bounds for length 3
- 空指针异常
public class Test {
public static void main(String[] args) {
int[] array = null;
System.out.println(array.length);
}
}
//执行结果:
//Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "array" is null
从上述过程中我们可以看到,java中不同类型的异常,都有与其对应的类来进行描述。
异常的体系结构
异常的种类繁多,为了对不同异常或者错误进行很好的分类管理,java内部维护了一个异常的体系结构:
从上图可以看到:
- Throwable:是异常体系的顶层类,其派生出两个重要的子类,Error和Exception
- Error:指的是java虚拟机无法解决的严重问题,比如:JVM的内部错误、资源耗尽等,典型代表:StackOverFlowError和OutOfMemoryError,一旦发生,回天乏术。
- Exception:异常产生后的程序员可以通过代码进行处理,使程序继续执行。我们平时所说的异常就是Exception。
异常的分类
异常可能在编译时发生,也可能在程序运行时发生,根据发生的时机不同,可以将异常分为:
- 编译时异常
在程序编译期间发生的异常,称为编译时异常,也称为受检查异常(Checked Exception)
public class Person {
public String name;
public int age;
@Override
protected Object clone() {
return super.clone();
}
//编译报错,java: 未报告的异常错误java.lang.CloneNotSupportedException; 必须对其进行捕获或声明以便抛出
}
protected native Object clone() throws CloneNotSupportedException;
//Object类中该方法声明了异常,所以使用该方法必须处理该异常或继续声明抛出异常
//正确写法:
public class Person {
public String name;
public int age;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
- 运行时异常
在程序执行期间发生的异常,称为运行时异常,也称为非受检查异常(Unchecked Exception)
RunTimeException以及子类对应的异常,都称为运行时异常。比如:NullPointerException、ArrayIndexOutOfBoundsException、ArithmeticException。
注意:编译时出现的语法性错误,不能称之为异常。例如将System写成system,此时编译过程中就会出错,这是编译期出错。而运行时指的是程序已经通过编译得到class文件了,再由JVM执行过程中出现的错误。
异常的处理
防御式编程
错误在代码中是客观存在的,因此我们要让程序出现问题的时候及时通知程序员。主要的方式:
- LBLY:Look Before You Leap。在操作之前做充分的检查,即:事前防御型
boolean ret = false;
ret = 登陆游戏();
if (!ret) {
处理登陆游戏错误;
return;
}
ret = 开始匹配();
if (!ret) {
处理匹配错误;
return;
}
ret = 游戏确认();
if (!ret) {
处理游戏确认错误;
return;
}
ret = 选择英雄();
if (!ret) {
处理选择英雄错误;
return;
......
缺陷:正常流程和错误处理流程混在一起,代码整体显得比较混乱。
- EAFP: It’s Easier to Ask Forgiveness than Permission.“事后获取原谅比事前获取许可更容易”,也就是先操作遇到问题再处理,即:事后认错型
try {
登陆游戏();
开始匹配();
游戏确认();
选择英雄();
载入游戏画面();
...
} catch (登陆游戏异常) {
处理登陆游戏异常;
} catch (开始匹配异常) {
处理开始匹配异常;
} catch (游戏确认异常) {
处理游戏确认异常;
} catch (选择英雄异常) {
处理选择英雄异常;
} catch (载入游戏画面异常) {
处理载入游戏画面异常;
}
......
优势:正常流程和错误流程是分离开的,程序员更关注正常流程,代码更清晰,更容易理解代码
异常处理的核心思想就是 EAFP。
在java中,异常处理主要的5个关键字:throw、try、catch、final、throws。
异常的抛出
在编写程序时,如果程序中出现错误,此时就需要将错误信息告知给调用者,比如:参数检测
在java中,可以借助 throw 关键字,指出一个指定的异常对象,将错误信息告知给调用者,具体语法如下:
throw new XXXExceptiom("异常产生的原因");
例子:需求:实现一个获取数组中任意位置元素的方法:
public class Test {
public static int getElement(int[] array, int index){
if(null == array){
throw new NullPointerException("传递的数组为null");
}
if(index < 0 || index >= array.length){
throw new ArrayIndexOutOfBoundsException("传递的数组下标越界");
}
return array[index];
}
public static void main(String[] args) {
int[] array = new int[]{1,2,3,4};
getElement(array,4);
}
//结果为:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 传递的数组下标越界
}
注意:
- throw必须写在方法体内部
- 抛出的对象必须是Exception 或者 Exception 的子类对象
- 如果抛出的是 RunTimeException 或者 RunTimeException 的子类,则可以不用处理,直接交给JVM来处理
- 如果抛出的是编译时异常,用户必须处理,否则无法通过编译
- 异常一旦抛出,其后的代码不会执行。
异常的捕获
异常的捕获也就是异常的具体处理方式,主要有两种:异常声明throws以及try-catch捕获处理。
异常声明throws
在方法声明时参数列表后,当方法中抛出编译时异常,用户不想处理该异常,此时就可以借助throws将异常抛给方法的调用者来处理。即当前方法不处理异常,提醒方法的调用者处理异常。
语法格式:
修饰符 返回值类型 方法名(参数列表)throws 异常类型1,异常类型2...{
}
需求:加载指定的配置文件config.ini
public class Config {
File file;
/*
FileNotFoundException:编译时异常,表明文件不存在
此处不处理,也没有能力处理,应将错误信息报告给调用者,让调用者检查文件名字是否给错误了
*/
public void openConfig(String fileName)throws FileNotFoundException{
if(fileName.equals("config.ini")){
throw new FileNotFoundException("配置文件名字不对");
}
//打开文件
}
public void readconfig(){
}
}
注意:
- throws 必须跟在方法的参数列表之后
- 声明的异常必须是Exception 或者 Exception 的子类
- 方法的内部如果抛出了多个异常,throws之后必须跟多个异常类型,之间用逗号隔开,如果抛出多个异常类型具有父子关系,直接声明父类即可。
public class Config {
File file;
/*
public void openConfig(String fileName)throws IOException,FileNotFoundException{
FileNotFoundException继承自IOException
*/
public void openConfig(String fileName)throws IOException{
if(fileName.equals("config.ini")){
throw new FileNotFoundException("配置文件名字不对");
}
//打开文件
}
public void readconfig(){
}
}
- 调用声明跑抛出异常的方法时,调用者必须对该异常进行处理,或者继续使用throws抛出
public class Test {
public static void main(String[] args) throws IOException {
Config config = new Config();
config.openConfig("config.ini");
}
}
try-catch捕获并处理
throws对异常并没有真正处理,而是将异常报告给抛出抛出异常方法的调用者,由调用者处理,如果真正要对异常进行处理,就需要try-catch。
语法格式:
try{
//将可能出现异常的代码放在这里
}catch(要捕获的异常类型 e){
//如果try中的代码抛出异常了,此处catch捕获的异常类型与try中抛出的类型一致时,或者是try中抛出异常的基类时,就会被捕获到
//对异常就可以正常处理,处理完成后,跳出try-catch结构,继续执行后序代码
}[catch(异常类型 e){
//对异常进行处理
}finally{
//此处代码一定会被执行到
}]
//后序代码
//当异常被捕获到时,异常就被处理了,这里的后序代码一定会被执行。
//如果捕获了,由于捕获类型不对,那就没有捕获到,这里的代码就不会被执行
//[]中表示可选项,可以添加,也可以不用添加
//try中的代码可能会抛出异常,也可能不会。
需求:读取配置文件,如果配置文件名字不是指定名字,抛出异常,调用者进行处理
public class Config {
File file;
public void openConfig(String fileName)throws FileNotFoundException{
if(fileName.equals("config.ini")){
throw new FileNotFoundException("配置文件名字不对");
}
//打开文件
}
public void readconfig(){
}
}
public class Test {
public static void main(String[] args) {
Config config = new Config();
try{
config.openConfig("config.ini");
System.out.println("文件打开成功");
}catch(IOException e){
//异常的处理方式
//System.out.println(e.getMessage()); //只打印异常信息
//System.out.println(e); //打印异常类型:异常信息
e.printStackTrace(); //打印信息最全面
}
//一旦异常被捕获处理了,此处的代码会执行
System.out.println("异常如果被处理了,这里的代码也可以执行");
}
}
关于异常的处理方式
异常的种类有很多,要根据不同的业务场景来决定
对于比较严重的问题,应该让程序直接崩溃,防止造成更严重的后果
对于不太严重的问题,可以记录错误日志,并通过监控报警程序及时通知程序员
对于可能会恢复的问题(网络相关场景),可以尝试进行重试
注意:
- try块内抛出异常位置之后的代码将不会被执行。
- 如果抛出的异常类型与catch时异常类型不匹配,即异常不会被成功捕获,也就不会被处理,继续往外抛,直到JVM收到后中断程序,异常是按照类型来捕获的。
public class Test {
public static void main(String[] args) {
int[] array = {1,2,3};
try{
System.out.println(array[3]);
}catch(NullPointerException e){
e.printStackTrace();
}
System.out.println("后序代码");
//运行结果:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
}
}
- try可能会抛出多个不同的异常对象,则必须使用多个catch来捕获,即多种异常,多次捕获,但是不可能同时抛出多个异常,try块中发生异常后的代码将不会执行。
public class Test {
public static void main(String[] args) {
int[] array = {1,2,3};
try{
System.out.println("before");
//array = null;
//System.out.println(array.length);
System.out.println(array[3]);
System.out.println("after");
}catch(NullPointerException e){
e.printStackTrace();
}catch(ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
System.out.println("后序代码");
//运行结果:
//before
//后序代码
//java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
// at demo1.Test.main(Test.java:19)
}
}
如果多个异常的处理方式是完全相同,也可以写成:
catch(NullPointerException | ArrayIndexOutOfBoundsException e){
...
}
如果异常之间具有父子关系,一定是子类在前catch,父类异常在后catch,否则语法错误:
public class Test {
public static void main(String[] args) {
int[] array = {1,2,3};
try{
System.out.println("before");
//array = null;
//System.out.println(array.length);
System.out.println(array[3]);
System.out.println("after");
}catch(Exception e){ //Exception 可以捕获到所以异常
e.printStackTrace();
}catch(ArrayIndexOutOfBoundsException e){ //这个异常已经被捕获到
e.printStackTrace();
}
System.out.println("后序代码");
//运行结果:
//java: 已捕获到异常错误java.lang.ArrayIndexOutOfBoundsException
}
}
- 可以通过一个catch捕获到所有异常,即多个异常,一次捕获(不推荐)
public class Test {
public static void main(String[] args) {
int[] array = {1,2,3};
try{
System.out.println("before");
//array = null;
//System.out.println(array.length);
System.out.println(array[3]);
System.out.println("after");
}catch(Exception e){ //Exception 可以捕获到所以异常
e.printStackTrace();
}
System.out.println("后序代码");
//运行结果:
//before
//后序代码
//java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
// at demo1.Test.main(Test.java:19)
}
}
由于Exception类是所有异常的父类,因此可以用这个类型表示捕捉所有异常
catch进行类型匹配时,不光会匹配相同类型的异常对象,也会捕捉目标异常类型的子类对象。
finally
在写程序时,有些特定的代码,不论是程序是否发生异常,都需要执行,比如程序中打开的资源:网络连接、数据库连接、IO流等,在程序正常或异常退出时,必须要对资源进行回收;另外由于异常会引发程序发生跳转,可能导致有些语句执行不到,finally就是用来解决这个问题的。
语法格式:
try{
//将可能出现异常的代码放在这里
}catch(要捕获的异常类型 e){
//如果try中的代码抛出异常了,此处catch捕获的异常类型与try中抛出的类型一致时,或者是try中抛出异常的基类时,就会被捕获到
//对异常就可以正常处理,处理完成后,跳出try-catch结构,继续执行后序代码
}[catch(异常类型 e){
//对异常进行处理
}finally{
//此处代码一定会被执行到
}]
//后序代码
//当异常被捕获到时,异常就被处理了,这里的后序代码一定会被执行。
//如果捕获了,由于捕获类型不对,那就没有捕获到,这里的代码就不会被执行
//[]中表示可选项,可以添加,也可以不用添加
//try中的代码可能会抛出异常,也可能不会。
public class Test {
public static void main(String[] args) {
int[] array = {1,2,3};
try{
array[100] = 0;
array[0] = 0;
}catch(Exception e){ //Exception 可以捕获到所以异常
e.printStackTrace();
}finally {
System.out.println("finally中的代码一定会被执行");
}
System.out.println("如果没有抛出异常,或者异常被处理了,try-catch代码后的代码也会执行");
//运行结果:
//finally中的代码一定会被执行
//如果没有抛出异常,或者异常被处理了,try-catch代码后的代码也会执行
//java.lang.ArrayIndexOutOfBoundsException: Index 100 out of bounds for length 3
// at demo1.Test.main(Test.java:16)
}
}
问题:既然finallly中的代码和异常处理后的try-catch后的后续代码都会被执行,那为什么还要有finally呢?
需求:实现getData方法,内部输入一个整型数字,然后将该数字返回,并再main方法中打印。
public class Test {
public static int getData(){
Scanner scanner = null;
try{
scanner = new Scanner(System.in);
int data = scanner.nextInt();
return data;
}catch(InputMismatchException e){
e.printStackTrace();
}finally{
System.out.println("finally中的代码");
}
System.out.println("try-catch-finally之后的代码");
if(null != scanner){
scanner.close();
}
return 0;
}
public static void main(String[] args) {
int data = getData();
System.out.println(data);
//运行结果:
//5
//finally中的代码
//5
}
}
上述程序,如果正常输入成功接收输入后程序就会返回了,try-catch-finally之后的代码根本就没有执行,即输入流没有被释放,造成资源泄露。
注意:finally中的代码一定会被执行,一般会在finally中进行一些资源清理的扫尾工作。
public class Test {
public static int func(){
try{
return 10;
}finally{
return 20;
}
}
public static void main(String[] args) {
System.out.println(func());
//运行结果:
//20
}
}
finally执行的时机时是在方法返回之前(try或者catch中如果有return会在这个return之前执行finally),但是如果finally中也存在return语句,那么就会执行finally中的return语句,从而不会执行到try中原有的return,一般不建议在finally中写return(被编译器当做一个警告)
异常的处理流程
关于调用栈
方法之间是存在相互调用的关系,这种调用关系我们可以用“调用栈”来描述,在JVM中有一块内存空间称为“虚拟机栈”专门存储方法之间的调用关系,当代码中出现异常的时候,我们就可以使用阿。printStackTrace();的方式查看出现异常代码的调用栈
如果本方法没有中没有出现合适的处理异常的方式,就会沿着调用栈向上传递
public class Test {
public static void func(){
int[] array = {1,2,3};
System.out.println(array[100]);
}
public static void main(String[] args) {
try{
func();
}catch(ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
System.out.println("try-catch后的代码");
//运行结果:
//java.lang.ArrayIndexOutOfBoundsException: Index 100 out of bounds for length 3
// at demo1.Test.func(Test.java:17)
// at demo1.Test.main(Test.java:21)
//try-catch后的代码
}
}
如果向上一直传递都没有合适的方法处理异常,最终就会交给JVM处理,程序就会异常终止(和我们最开始未使用try-catch时是一样的)
public class Test {
public static void func(){
int[] array = {1,2,3};
System.out.println(array[100]);
}
public static void main(String[] args) {
func();
System.out.println("try-catch后的代码");
//运行结果:
//java.lang.ArrayIndexOutOfBoundsException: Index 100 out of bounds for length 3
// at demo1.Test.func(Test.java:17)
// at demo1.Test.main(Test.java:21)
}
}
可以看到程序已经异常终止了,并没有执行到System.out.println(“try-catch后的代码”);这行代码上。
异常处理流程总结:
- 程序先执行try中的代码
- 如果try中的代码出现异常,就会结束try中的代码,看和catch中的异常类型是否匹配
- 如果找到匹配的异常类型,就会执行catch中的代码
- 如果没有找到匹配的异常类型,就会将异常向上传递到上层调用者
- 无论是否找到匹配的异常类型,finally中的代码都会被执行到(在该方法结束之前执行)
- 如果上层调用者也没有处理的了的异常,就继续向上传递
- 一直到main方法也没有合适的代码处理异常,就交给JVM来进行处理,此时程序就会异常终止。
自定义异常类
java中虽然已经内置了丰富的异常类,但是并不能完全表示实际开发中所遇到的一些异常,此时就需要维护符合我们实际情况的异常结构。
需求:用户登录
public class Login {
private String name;
private String password;
public void setName(String name) {
this.name = name;
}
public void setPassword(String password) {
this.password = password;
}
public void loginInfo(String name, String password){
if(!this.name.equals(name)){
}
if(!this.password.equals(password)){
}
System.out.println("登录成功");
}
}
public class Test {
public static void main(String[] args) {
Login usr1 = new Login();
usr1.setName("张三");
usr1.setPassword("123456");
usr1.loginInfo("张三","123456");
//运行结果:
//登录成功
}
}
此时我们在处理用户名密码错误的时候就可能需要抛出两种异常,我们就可以基于已有的异常类进行拓展(继承),创建和我们业务相关的异常类。
具体方式:
- 自定义异常类,然后继承自 Exception 或者 RunTimeException
- 实现一个带有String类型参数的构造方法,参数含义:出现异常的原因
public class UserNameException extends RuntimeException{
public UserNameException(String message) {
super(message);
}
}
public class PasswordException extends RuntimeException{
public PasswordException(String message) {
super(message);
}
}
public class Login {
private String name;
private String password;
public void setName(String name) {
this.name = name;
}
public void setPassword(String password) {
this.password = password;
}
public void loginInfo(String name, String password){
if(!this.name.equals(name)){
throw new UserNameException("用户名错误!");
}
if(!this.password.equals(password)){
throw new PasswordException("密码错误!");
}
System.out.println("登录成功");
}
}
public class Test {
public static void main(String[] args) {
Login usr1 = new Login();
usr1.setName("张三");
usr1.setPassword("123456");
try{
usr1.loginInfo("张三","123456");
}catch(UserNameException e){
e.printStackTrace();
}catch(PasswordException e){
e.printStackTrace();
}
//运行结果:
//登录成功
}
}
注意:
- 自定义异常通常会继承自Exception 或者 RunTimeException
- 继承自Exception 的异常默认是受查异常
- 继承自RunTimeException 的异常默认是非受查异常
关于异常我们先了解到这里,我们后续对的理解和运用也会越来越深刻和熟练,永不言弃,不断学习,never give up!!