Java之异常处理

一、认识异常

1.异常的概念

Java 中,将程序执行过程中发生的不正常行为称为异常。。比如之前写代码时经常遇到的:
1. 算术异常
System.out.println(10 / 0);
// 执行结果
Exception in thread "main" java.lang.ArithmeticException: / by zero
2. 数组越界异常
int[] arr = {1, 2, 3};
System.out.println(arr[100]);
// 执行结果
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
3. 空指针异常
int[] arr = null;
System.out.println(arr.length);
// 执行结果
Exception in thread "main" java.lang.NullPointerException
从上述过程中可以看 到,java中不同类型的异常,都有与其对应的类来进行描述。 

2.异常的体系结构

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

6703cef0fe1b47f180dfdcfc4bcbbebd.png

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

3. 异常的分类

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

1. 编译时异常

在程序编译期间发生的异常,称为编译时异常,也称为受检查异常, 该异常必须要被捕获或者声明,否则无法运行。
class Person implements Cloneable{
    public String name;

    public Person(String name) {
        this.name = name;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
public static void main(String[] args)  {
        Person person1 = new Person("zhangsan");
        Person person2 = (Person)person1.clone();

    }
// 因为main方法没有使用throws CloneNotSupportedException,这个程序将不能运行,在编译时就会报错。后面会讲到throws
//或者下面这样写
class Person implements Cloneable {
    public String name;
    public Person(String name) {
        this.name = name;
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}public static void main(String[] args) { //这里没有声明,但是捕获了
    Person person1 = new Person("zhangsan");
    try {
        Person person2 = (Person) person1.clone();
    } catch (CloneNotSupportedException e) {
        // 在这里处理CloneNotSupportedException
        System.err.println("Clone operation failed: " + e.getMessage());
    }
}

2. 运行时异常

在程序执行期间发生的异常,称为运行时异常,也称为非受检查异常,即可以运行但结果会抛出异常。
RunTimeException 以及其子类对应的异常,都称为运行时异常。比如:NullPointerException、
ArrayIndexOutOfBoundsException、ArithmeticException。
注意:编译时出现的语法性错误,不能称之为异常。例如将 System.out.println 拼写错了, 写成了system.out.println. 此时编译过程中就会出错.

二、 异常的处理

1.异常的抛出

在自定义异常类中必须使用throw来抛出异常(后面讲到)。在Java中,可以借助throw关键字,抛出一个指定的异常对象。具体语法如下:

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

例题:实现一个获取数组中任意位置元素的方法。

public class App {
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 = {1,2,3};
getElement(array, 3);
}
}
//输出结果
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 传递的数组下标越界
	at App.getElement(App.java:7)
	at App.main(App.java:13)
注意事项
1. throw必须写在方法体内部
2. 抛出的对象必须是Exception 或者 Exception 的子类对象
3. 如果抛出的是 RunTimeException 或者 RunTimeException 的子类,则可以不用处理,直接交给JVM来处理
4. 如果抛出的是编译时异常,用户必须处理,否则无法通过编译
5. 异常一旦抛出,其后的代码就不会执行

2.异常的声明

处在方法声明时参数列表之后,当方法中抛出编译时异常,用户不想处理该异常,此时就可以借助throws将异常抛给方法的调用者(上级)来处理。即 当前方法不处理异常,提醒方法的调用者(上级)处理异常
语法格式:
修饰符 返回值类型 方法名(参数列表) throws 异常类型1,异常类型2...{
}
注意事项
1. throws必须跟在方法的参数列表之后
2. 声明的异常必须是 Exception 或者 Exception 的子类
3. 方法内部如果抛出了多个异常,throws之后必须跟多个异常类型,之间用逗号隔开, 如果抛出多个异常类型具有父子关系,直接声明父类即可。
4. 调用声明抛出异常的方法时,调用者必须对该异常进行处理,或者继续使用throws抛出,如果到最高级也没有捕获异常,将交给jvm 处理,程序就会异常终止(和我们最开始未使用 try atch 时是一样的)

3.异常的处理

throws对异常并没有真正处理,而是将异常报告给抛出异常方法的调用者,由调用者处理。如果真正要对异常进行处理,就需要try-catch。其中e为异常类型的变量。可以通过e调用异常类的方法,你可以调用e.getMessage()来获取异常的描述信息,通过e.printStackTrace()来打印异常的位置。
语法格式:
try{
// 将可能出现异常的代码放在这里
}catch(要捕获的异常类型 e){
// 如果try中的代码抛出异常了,此处catch捕获时异常类型与try中抛出的异常类型一致时,或者是try中抛出异常的基类
时,就会被捕获到
// 对异常就可以正常处理,处理完成后,跳出try-catch结构,继续执行后序代码
}[catch(异常类型 e){
// 对异常进行处理
}finally{
// 此处代码一定会被执行到
}]
// 后序代码
// 当异常被捕获到时,异常就被处理了,这里的后序代码一定会执行
// 如果捕获了,由于捕获时类型不对,那就没有捕获到,这里的代码就不会被执行
注意:
1. []中表示可选项,可以添加,也可以不用添加
2. try中的代码可能会抛出异常,也可能不会

例题:演示throws作用

class app {
    public static void main(String[] args) throws ArrayIndexOutOfBoundsException {
func();
    }
    public static void func(){
        try {

            int[] arr = {1, 2, 3};
            System.out.println(arr[100]);
        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        }
        System.out.println("after try catch");
    }
}

当然,上面代码可以省略throws(仅对运行时异常适用),在编译时异常中就不能省略了。

注意事项:
1. try块内抛出异常位置之后的代码将不会被执行
2. 如果抛出异常类型与catch时异常类型不匹配,即异常不会被成功捕获,也就不会被处理,继续往外抛,直到JVM收到后中断程序----异常是按照类型来捕获的

public static void main(String[] args) {
try {
int[] array = {1,2,3};
System.out.println(array[3]); // 此处会抛出数组越界异常
}catch (NullPointerException e){ // 捕获时候捕获的是空指针异常--真正的异常无法被捕获到
e.printStackTrace();
}
System.out.println("后序代码");
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at day20210917.ArrayOperator.main(ArrayOperator.java:24)
3.当你不确定异常类型时,可以用多个catch来捕获----多次捕获。直到匹配正确为止。
public static void main(String[] args) {
int[] arr = {1, 2, 3};
try {
System.out.println(arr[100]);
} catch (NullPointerException e) {
System.out.println("这是个空指针异常");
e.printStackTrace();
}catch (ArrayIndexOutOfBoundsException e) {
System.out.println("这是个数组下标越界异常");
e.printStackTrace();
}
System.out.println("after try catch");
}
也可以写成这样:
catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
...//只要一个匹配正确,就会执行这行代码
}
如果异常之间具有父子关系,一定是子类异常在前catch,父类异常在后catch,否则语法错误:因为父类在前的话,后面子类这个代码没意义了,会报错
public static void main(String[] args) {
int[] arr = {1, 2, 3};
try {
System.out.println("before");
arr = null;
System.out.println(arr[100]);
System.out.println("after");
} catch (Exception e) { // Exception可以捕获到所有异常
e.printStackTrace();
}catch (NullPointerException e){ // 永远都捕获执行到
e.printStackTrace();
}
System.out.println("after try catch");
}
Error:(33, 10) java: 已捕获到异常错误java.lang.NullPointerException
4. 可以通过一个catch捕获所有的异常,即多个异常,一次捕获(不推荐)
public static void main(String[] args) {
int[] arr = {1, 2, 3};
try {
System.out.println("before");
arr = null;
System.out.println(arr[100]);
System.out.println("after");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("after try catch");
}
由于 Exception 类是所有异常类的父类. 因此可以用这个类型表示捕捉所有异常。
备注: catch 进行类型匹配的时候, 不光会匹配相同类型的异常对象, 也会捕捉目标异常类型的子类对象.

4. finally

在写程序时,有些特定的代码,不论程序是否发生异常,都需要执行。另外,因为 异常会引发程序的跳转,可 导致有些语句执行不到,finally 就是用来解决这个问题的。
语法格式:
try{
// 可能会发生异常的代码
}catch(异常类型 e){
// 对捕获到的异常进行处理
}finally{
// 此处的语句无论是否发生异常,都会被执行到
}
// 如果没有抛出异常,或者异常被捕获处理了,这里的代码也会执行
public static void main(String[] args) {
System.out.println(func());
}
public static int func() {
try {
return 10;
} finally {
return 20;
}
}
//输出结果
20
上面代码中finally 执行的时机是在方法返回之前 (try 或者 catch 中如果有 return 会在这个 return 之前执行 finally). 但是如果finally 中也存在 return 语句 , 那么就会执行 finally 中的 return, 从而不会执行到 try 中原有的 return.

三、自定义异常类

Java 中虽然已经内置了丰富的异常类 , 但是并不能完全表示实际开发中所遇到的一些异常,此时就需要维护符合我们实际情况的异常结构.
例如 , 我们实现一个用户登陆功能 .
import java.util.Scanner;

// 自定义异常类用于处理登录失败的情况
class LoginException extends Exception {
    public LoginException(String message) {
        super(message);
    }
}

public class SimpleLoginWithException {
    public static void main(String[] args) {
        // 预设的正确用户名和密码
        String correctUsername = "admin";
        String correctPassword = "password123";

        Scanner scanner = new Scanner(System.in);
//一定要处理检查异常
        try {
            System.out.print("请输入用户名: ");
            String username = scanner.nextLine();
,
            System.out.print("请输入密码: ");
            String password = scanner.nextLine();

            // 检查用户名和密码是否正确
            if (!correctUsername.equals(username) || !correctPassword.equals(password)) {
                throw new LoginException("登录失败!用户名或密码错误。");
            }

            System.out.println("登录成功!");
        } catch (LoginException e) {
            System.out.println(e.getMessage());
        } finally {
            // 关闭scanner
            scanner.close();
        }
    }
}
具体方式:
1. 自定义异常类,然后继承自 Exception 或者 RunTimeException
2. 实现一个带有 String 类型参数的构造方法,参数含义:出现异常的原因
注意事项
自定义异常通常会继承自 Exception 或者 RuntimeException
继承自 Exception 的异常默认是受查异常,一定要处理或者声明。
继承自 RuntimeException 的异常默认是非受查异常,不处理也能运行,可以不用声明。

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值