Java_认识异常

目录

一、异常的概念与体系结构

1.1 异常的概念

1.2 异常的体系结构

1.3 异常的分类

二、异常的处理

2.1 防御式编程

2.2 异常的抛出

2.3 异常的捕获

2.3.1异常声明throws

2.3.2 捕获异常

2.3.3 finally

2.4 异常的处理流程

三、 自定义异常类


一、异常的概念与体系结构

1.1 异常的概念

Java 中,将程序执行过程中发生的不正常行为称为异常
public class Main {
    public static void main(String[] args) {
        System.out.println(10/0);

    }
}

 public static void main(String[] args) {
        int[] arr = new int[3];
        System.out.println(arr[3]);
    }

 public static void main(String[] args) {
        int[] arr = null;
        System.out.println(arr[0]);
    }

从上述例子中不难看出

java 中不同类型的异常,都有与其对应的类来进行描述

1.2 异常的体系结构

异常种类繁多,为了对不同异常或者错误进行很好的分类管理,Java内部维护了一个异常的体系结

构:

1. Throwable 是异常体系的顶层类,其派生出两个重要的子类 , Error Exception
2. Error 指的是 Java 虚拟机无法解决的严重问题,比如: JVM 的内部错误、资源耗尽等 ,典型代表:
StackOverflowError OutOfMemoryError ,一旦发生回力乏术。
3. Exception 异常产生后程序员可以通过代码进行处理,使程序继续执行。比如:感冒、发烧。
我们平时所说的异常就是Exception。

1.3 异常的分类

异常可能在编译时发生,也可能在程序运行时发生,根据发生的时机不同,可以将异常分为:

编译时异常
在程序编译期间发生的异常,称为编译时异常,也称为受检查异常(Checked Exception)
public class Person implements Cloneable {
    public String name;
    public int age;
 
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
 
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
 
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

public class Main  {
    public static void main(String[] args)  throws CloneNotSupportedException{
      Person person1 = new Person("张三",18);
      Person person2 = (Person) person1.clone();
    }
}

运行时异常
在程序执行期间发生的异常,称为运行时异常,也称为非受检查异常(Unchecked Exception)

RunTimeException 以及其子类对应的异常,都称为运行时异常 。比如: NullPointerException
ArrayIndexOutOfBoundsException ArithmeticException
注意:编译时出现的语法性错误,不能称之为异常。

二、异常的处理

2.1 防御式编程

LBYL : Look Before You Leap. 在操作之前就做充分的检查 . 即: 事前防御型
boolean ret = false;
ret = 登陆游戏();
if (!ret) {
处理登陆游戏错误;
return;
}
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中采用的便是 EAFP
Java 中, 异常处理主要的 5 个关键字: throw try catch final throws

2.2 异常的抛出

Java中,可以借助throw关键字,抛出一个指定的异常对象,将错误信息告知给调用者。

抛出的异常的方式有以下

某段程序触发

如1.1中所举例

通过关键字 throw 抛出

语法如下

throw new XXXException("异常产生的原因");

public class Test1 {
    public static void main(String[] args) {
       int a = 10;
       if(a == 10){
           throw new NullPointerException("测试!");//这里仅为演示手动抛出异常的方法
       }
    }
}

 

确实手动抛出了一个异常

throw 一般用于抛出自定义的异常

1.throw 必须写在方法体内部

2. 抛出的对象必须是  Exception 或者 Exception 的子类对象(即抛出的一定是个异常)
3. 如果抛出的是 RunTimeException 或者 RunTimeException 的子类,则可以不用处理,直接 
交给JVM来处理
4. 如果抛出的是编译时异常,用户必须处理,否则无法通过编译
5. 异常一旦抛出,其后的代码就不会执行

2.3 异常的捕获

异常的捕获,也就是异常的具体处理方式,主要有两种:异常声明 throws 以及 try-catch 捕获处

2.3.1异常声明throws

处在方法声明时参数列表之后,当方法中抛出编译时异常,用户不想处理该异常,此时就可以借助
throws 将异常抛给方法的调用者来处理。即当前方法不处理异常,提醒方法的调用者处理异常
语法格式:

修饰符 返回值类型 方法名(参数列表) throws 异常类型1,异常类型2...{

}
public class Main  {
    public static void main(String[] args)  throws CloneNotSupportedException{
      Person person1 = new Person("张三",18);
      Person person2 = (Person) person1.clone();
    }
}

 如果一个方法内部存在一个编译时异常,此时这个编译时异常一定要进行处理

目前处理方式是在方法定义时,通过 throws 关键字声明异常

最后这个异常是交给 JVM 处理的

1. throws  必须跟在方法的参数列表之后
2. 声明的异常必须是 Exception 或者 Exception 的子类(即必须是异常)
3. 方法内部如果抛出了多个异常, throws  之后必须跟多个异常类型,之间用逗号隔开,如果抛出 
多个异常类型具有父子关系,直接声明父类即可。
4. 调用声明抛出异常的方法时,调用者必须对该异常进行处理,或者继续使用 throws 抛出
public class Main  {
  public static void main(String[] args) {
    main1();
  }
    public static void main1()  throws CloneNotSupportedException{
      Person person1 = new Person("张三",18);
      Person person2 = (Person) person1.clone();

    }
}

为什么这里继续报错
因为在调用 main1 这个会抛出异常的方法时
既没有处理这个异常
又没有使用 throws 继续抛出
那在这里先说使用 throws 继续抛出

可以看到,这里编译就通过了,没有报错

那么在这里

并没有处理掉这个异常

最终还是交给 JVM 处理的

那么如何自己处理异常?

2.3.2 捕获异常

throws  对异常并没有真正处理,而是将异常报告给抛出异常方法的调用者,由调用者处理。如果
真正要对异常进行处理,就需要 try-catch 
public static void main(String[] args) {
    try {
      main1();
    }catch (CloneNotSupportedException e){
      System.out.println("处理了CloneNotSupportedException 异常!");
    }
  }

那么通过 try-catch 手动处理和交给 JVM 处理有什么区别呢

public static void main(String[] args) {
        System.out.println("first!");

        int a = 10 / 0;

        System.out.println("last!");
    }

 public static void main(String[] args) {
        System.out.println("first!");
        try {
            int a = 10 / 0;

        }catch (ArithmeticException e){
            System.out.println("我处理了ArithmeticException 异常!");
        }
        System.out.println("last!");

    }

通过这里可以对比出

交给 JVM 处理异常

这个异常发生

程序就会异常终止

而通过 try-catch 手动处理异常后

程序还可以正常运行

那么如果想知道异常出现在哪个位置该怎么办呢

可以使用  e.printStackTrace();

 此处就可以报出异常出现的位置

try 中异常发生后的代码不会执行

 public static void main(String[] args) {
        System.out.println("first!");
        try {
            int a = 10 / 0;
            System.out.println("666");

        }catch (ArithmeticException e){
            System.out.println("我处理了ArithmeticException 异常!");
            e.printStackTrace();
        }
        System.out.println("last!");

    }

那么这两种方法不存在绝对的优劣之分,需要根据具体的需求选择使用

对于比较严重的问题(例如和算钱相关的场景), 应该让程序直接崩溃, 防止造成更严重的后果

对于不太严重的问题 ( 大多数场景 ), 可以记录错误日志 , 并通过监控报警程序及时通知程序猿
对于可能会恢复的问题 ( 和网络相关的场景 ), 可以尝试进行重试 .

注:

如果抛出异常类型与  catch  时异常类型不匹配,即异常不会被成功捕获,也就不会被处理,继续
往外抛,直到 JVM 收到后中断程序----异常是按照类型来捕获的
    public static void main(String[] args) {
        System.out.println("first!");
        try {
            int a = 10 / 0;

        }catch (NullPointerException e){
            System.out.println("我处理了ArithmeticException 异常!");
            e.printStackTrace();
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println("我处理了ArrayIndexOutOfBoundsException 异常!");
            e.printStackTrace();
        }
        System.out.println("last!");

    }

try  中可能会抛出多个不同的异常对象,则必须用多个  catch  来捕获 ---- 即多种异常,多次捕获
注:虽然 可以捕获多个异常
但是 同一时刻 只能抛出一个异常!!!
 public static void main(String[] args) {
        try {
            int[] arr = null;
            arr[1/0] = 1;
        }catch (NullPointerException e){
            System.out.println("我处理了NullPointerException 异常! ");
        }catch (ArithmeticException e){
            System.out.println("我处理了ArithmeticException 异常! ");

        }
    }

catch (NullPointerException e | ArithmeticException e)

捕获多种异常也可以这样写

不过比较少见

如果异常之间具有父子关系,一定是子类异常在前  catch  ,父类异常在后  catch  ,否则语法错误:
此处就相当于是一个兜底的作用
能够保证有异常发生就捕获到
但是不建议直接使用父类捕获异常
因为此时异常不精准

2.3.3 finally

在写程序时, 有些特定的代码,不论程序是否发生异常,都需要执行
或者,因为 异常会引发程序的跳转,可能 导致有些语句执行不到 finally 就是用来解决这个问题
的。
public static void main(String[] args) {
        fun();
    }
    public static void fun(){
        System.out.println("first!");
        try {
           
            return;

        } catch (ArithmeticException e) {
            System.out.println("我处理了ArithmeticException 异常!");
        } finally {
            System.out.println("执行了finally");
        }
        System.out.println("last!");
    }

这里可以看到,fun 方法结束后仍然执行了 finally 的代码

finally 中的代码总是会被执行
不建议在 finally 中写 return
    public static int  fun2(){
        try {
            System.out.println(10/0);
        }catch (ArithmeticException e){
            System.out.println("这里返回1");
            return 1;
        }
        finally {
            return 0;
        }
    }
  public static void main(String[] args) {

        System.out.println("实际返回值是"+fun2());

    }

finally 执行的时机是在方法返回之前(try 或者 catch 中如果有 return 会在这个 return 之前执行

finally). 但是如果finally 中也存在 return 语句, 那么就会执行 finally 中的 return, 从而不会执行到

try中原有的 return.

2.4 异常的处理流程

如果本方法中没有合适的处理异常的方式 , 就会沿着调用栈向上传递
 public static void func() {
        int[] arr = {1, 2, 3};
        System.out.println(arr[100]);
    }

    public static void main(String[] args) {
        func();
    }

如果向上一直传递都没有合适的方法处理异常, 最终就会交给 JVM 处理, 程序就会异常终止 

 

这里先调用的 main 方法

再调用的是 func 方法

这里的向上传递值得是向上层调用者传递

public static void func() {
        int[] arr = {1, 2, 3};
        System.out.println(arr[100]);
    }

    public static void main(String[] args) {
        try {
            func();
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println("我来处理ArrayIndexOutOfBoundsException 异常了!");
        }
        
    }

那么这里既然可能会出现抛出异常的情况

就可以给 func 方法用 throws 关键字声明一下


    public static void func() throws  ArrayIndexOutOfBoundsException {
        int[] arr = {1, 2, 3};
        System.out.println(arr[100]);
    }

    public static void main(String[] args) {
        try {
            func();
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println("我来处理ArrayIndexOutOfBoundsException 异常了!");
        }

    }

程序先执行 try 中的代码
如果 try 中的代码出现异常 , 就会结束 try 中的代码 , 看和 catch 中的异常类型是否匹配 .
如果找到匹配的异常类型 , 就会执行 catch 中的代码
如果没有找到匹配的异常类型 , 就会将异常向上传递到上层调用者 .
无论是否找到匹配的异常类型 , finally 中的代码都会被执行到 ( 在该方法结束之前执行 ).
如果上层调用者也没有处理的了异常 , 就继续向上传递 .
一直到 main 方法也没有合适的代码处理异常 , 就会交给 JVM 来进行处理 , 此时程序就会异常终止 .

三、 自定义异常类

Java 中虽然已经内置了丰富的异常类 , 但是并不能完全表示实际开发中所遇到的一些异常,此时就
需要维护符合我们实际情况的异常结构
假设需要实现一个用户登陆功能 .
那么在这个过程中可能会出现两种异常
用户名不匹配
密码不匹配
在不适用异常的情况下
public class User {

    public static void main1(String[] args) {
        
    }
    private String username = "Java";
    private String password ="123456";

    public void Verify(String username,String password){
        if(!this.username.equals(username)){
            System.out.println("用户名错误!");
        }
        if(!this.password.equals(password)){
            System.out.println("密码错误!");
        }
        if(this.username.equals(username) && this.password.equals(password)){
            System.out.println("登录成功!");
        }
    }

}
可能会如上述所写
那么可以基于已有的异常类进行扩展(继承),创建需要的异常类
步骤如下:
自定义异常类,然后继承自  Exception(编译时异常) 
或者 RunTimeException (运行时异常)
实现一个带有 String 类型参数的构造方法,参数含义:出现异常的原因
public class UserPasswordException extends Exception{
    public UserPasswordException(String message) {
        super(message);
    }
}
public class UserNameException extends Exception{
    public UserNameException(String message) {
        super(message);
    }
}

  public void Verify2(String username,String password) {
        if(!this.username.equals(username)){
            throw new UserNameException("用户名错误!");
        }
        if(!this.password.equals(password)){
            throw  new UserPasswordException("密码错误!");
        }
        if(this.username.equals(username) && this.password.equals(password)){
            System.out.println("登录成功!");
        }
    }

此时继承的是 Exception

所以在使用时需要使用 throws 声明一下这个异常

public void Verify2(String username, String password) throws UserPasswordException,UserNameException {
        if(!this.username.equals(username)){
            throw new UserNameException("用户名错误!");
        }
        if(!this.password.equals(password)){
            throw  new UserPasswordException("密码错误!");
        }
        if(this.username.equals(username) && this.password.equals(password)){
            System.out.println("登录成功!");
        }
    }

在调用方法时也需要进行捕获

public static void main(String[] args) {
        User user = new User();
        try {
            user.Verify2("123", "666");
        } catch (UserNameException e) {
            e.printStackTrace();
        } catch (UserPasswordException e) {
            e.printStackTrace();
        }
    }

那么如果是继承的 RunTimeException (运行时异常)

public class UserNameException extends RuntimeException{
    public UserNameException(String message) {
        super(message);
    }
}
public class UserPasswordException extends RuntimeException{
    public UserPasswordException(String message) {
        super(message);
    }
}

就可以不使用  try-catch 进行捕获

public static void main(String[] args) {
        User user = new User();
        user.Verify3("123","666");
    }

直接这样写也不会报错

本文只是概述一下异常的使用,到此结束

  • 13
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值