JavaSE之认识异常

目录

一、什么是异常

二、异常的好处

三、捕获异常

1.基本语法

2、一些注意事项

3.异常处理流程

4.抛出异常

5.异常说明

6.关于finally的注意事项

四、Java异常体系

五、自定义异常类  


一、什么是异常

1、所谓异常指的就是程序在 运行时 出现错误时通知调用者的一种机制
注意: 有些错误是这样的, 例如将 System.out.println 拼写错了, 写成了 system.out.println. 此时编译过程中就会出错, 这是 "编译期" 出错.而运行时指的是程序已经编译通过得到 class 文件了, 再由 JVM 执行过程中出现的错误
2、 错误在代码中是客观存在的 . 因此我们要让程序出现问题的时候及时通知程序猿 . 我们有两种主要的方式
LBYL : Look Before You Leap. 在操作之前就做充分的检查 .
EAFP : It's Easier to Ask Forgiveness than Permission. " 事后获取原谅比事前获取许可更容易 ". 也就是先操作 , 遇到
问题再处理 .
异常的核心思想就是 EAFP.

二、异常的好处

我们看一下下面的伪代码对比:
1.LBYL 风格的代码 ( 不使用异常 )
boolean ret = false;
ret = 登陆游戏();
if (!ret) {
    处理登陆游戏错误;
    return; 
}
ret = 开始匹配();
if (!ret) {
    处理匹配错误;
    return; 
}
ret = 游戏确认();
if (!ret) {
    处理游戏确认错误;
    return; 
}
ret = 选择英雄();
if (!ret) {
    处理选择英雄错误;
    return; 
}
ret = 载入游戏画面();
if (!ret) {
    处理载入游戏错误;
    return; 
}
......

2.EAFP 风格的代码(使用异常)

try {
    登陆游戏();
    开始匹配();
    游戏确认();
    选择英雄();
    载入游戏画面();
   ...
} catch (登陆游戏异常) {
    处理登陆游戏异常;
} catch (开始匹配异常) {
 处理开始匹配异常;
} catch (游戏确认异常) {
 处理游戏确认异常;
} catch (选择英雄异常) {
 处理选择英雄异常;
} catch (载入游戏画面异常) {
 处理载入游戏画面异常; }
......
对比两种不同风格的代码 , 我们可以发现 , 使用第一种方式 , 正常流程和错误处理流程代码混在一起 , 代码整体显的比较混乱. 而第二种方式正常流程和错误流程是分离开的 , 更容易理解代码

三、捕获异常

1.基本语法

try{ 
     有可能出现异常的语句 ; 
}catch (异常类型 异常对象) {
     ......
} 
[finally {
     异常的出口
}]
(1)try 代码块中放的是可能出现异常的代码 .
(2)catch 代码块中放的是出现异常后的处理行为 .
(3)finally 代码块中的代码用于处理善后工作 , 会在最后执行 .
(4)其中 finally 可以根据情况选择加或者不加
如:
public class TestDemo {
    public static void main(String[] args) {
        int[] array = {1,2,3};
        try{
            System.out.println(array[5]);
            System.out.println("haha");//此处不能被打印
        }catch(ArrayIndexOutOfBoundsException e){
            System.out.println("捕捉到一个数组越界异常");
        }
        System.out.println("hehe");
    }
}
一旦 try 中出现异常 , 那么 try 代码块中的程序就不会继续执行 , 而是交给 catch 中的代码来执行 . catch 执行完毕会继续往下执行(如果不处理异常,那么这个异常会交给JVM,一旦交给JVM处理,程序立马就终止了)

编译并运行该代码,输出如下:

捕捉到一个数组越界异常
hehe 

其实ArrayIndexOutOfBoundsException是一个类 

关于异常的处理方式
异常的种类有很多, 我们要根据不同的业务场景来决定.
对于比较严重的问题(例如和算钱相关的场景), 应该让程序直接崩溃, 防止造成更严重的后果
对于不太严重的问题(大多数场景), 可以记录错误日志, 并通过监控报警程序及时通知程序猿对于可能会恢复的问题(和网络相关的场景), 可以尝试进行重试.
在我们当前的代码中采取的是经过简化的第二种方式. 我们记录的错误日志是出现异常的方法调用信息, 能很快速的让我们找到出现异常的位置. 以后在实际工作中我们会采取更完备的方式来记录异常信息

2、一些注意事项

(1)"调用栈"

方法之间是存在相互调用关系的, 这种调用关系我们可以用 "调用栈" 来描述. 在 JVM 中有一块内存空间称为 "虚拟机栈" 专门存储方法之间的调用关系. 当代码中出现异常的时候, 我们就可以使用 e.printStackTrace(); 的方式查看出现异常代码的调用栈
如:上面的代码,我们还可以这样写:
public class TestDemo {
    public static void main(String[] args) {
        int[] array = {1,2,3};
        try{
            System.out.println(array[5]);
            System.out.println("haha");
        }catch(ArrayIndexOutOfBoundsException e){
            e.printStackTrace();
            System.out.println("捕捉到一个数组越界异常");
        }
        System.out.println("hehe");
    }
}

编译并运行该代码,输出如下:

 我们再举个例子;

import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        System.out.println(n);
    }
}

 编译并运行该代码,输出如下:

 (2)catch 只能处理对应种类的异常

public class TestDemo {
    public static void main(String[] args) {
        int[] array = {1,2,3};
        try{
            array = null;
            System.out.println(array[2]);
        }catch(ArrayIndexOutOfBoundsException e){
            e.printStackTrace();
            System.out.println("捕捉到一个数组越界异常");
        }
        System.out.println("hehe");
    }
}

  编译并运行该代码,输出如下:

此时, catch 语句不能捕获到刚才的空指针异常. 因为异常类型不匹配 

(3)catch 可以有多个

public class TestDemo {
    public static void main(String[] args) {
        int[] array = {1,2,3};
        try{
            array = null;
            System.out.println(array[2]);
        }catch(ArrayIndexOutOfBoundsException e){
            e.printStackTrace();
            System.out.println("捕捉到一个数组越界异常");
        }catch (NullPointerException e){
            e.printStackTrace();
            System.out.println("捕捉到一个空指针异常");
        }
        System.out.println("hehe");
    }
}

  编译并运行该代码,输出如下:

如果多个异常的处理方式是完全相同, 也可以写成这样:

public class TestDemo {
    public static void main(String[] args) {
        int[] array = {1,2,3};
        try{
            array = null;
            System.out.println(array[2]);
        }catch(ArrayIndexOutOfBoundsException | NullPointerException e){
            e.printStackTrace();
            System.out.println("捕捉到一个数组越界异常或者空指针异常");
        }
        System.out.println("hehe");
    }
}

 (4)也可以用一个 catch 捕获所有异常(不推荐)

public class TestDemo {
    public static void main(String[] args) {
        int[] array = {1,2,3};
        try{
            array = null;
            System.out.println(array[2]);
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("发生异常");
        }
        System.out.println("hehe");
    }
}

   编译并运行该代码,输出如下:

 如果没有e.printStackTrace();这条语句,我们根本不知道发生了什么异常

由于 Exception 类是所有异常类的父类 . 因此可以用这个类型表示捕捉所有异常
(5)finally 表示最后的善后工作 , 例如释放资源
import java.util.InputMismatchException;
import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        try{
            int n = scanner.nextInt();
            System.out.println(10/n);
        }catch(InputMismatchException e){
            e.printStackTrace();
            System.out.println("输出错误!");
        }catch(ArithmeticException e){
            e.printStackTrace();
            System.out.println("算术异常!");
        }finally{
            //finally一般用作资源的关闭,也可以不写finally,只写scanner.close();
            scanner.close();
        }
    }
}
无论是否存在异常 , finally 中的代码一定都会执行到 . 保证最终一定会执行到 Scanner close 方法
(6)使用 try 负责回收资源
上面的代码可以有一种等价写法 , Scanner 对象在 try ( ) 中创建 , 就能保证在 try 执行完毕后自动调用 Scanner 的 close 方法
import java.util.InputMismatchException;
import java.util.Scanner;

public class TestDemo {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            int n = scanner.nextInt();
            System.out.println(10 / n);
        } catch (InputMismatchException e) {
            e.printStackTrace();
            System.out.println("输出错误!");
        } catch (ArithmeticException e) {
            e.printStackTrace();
            System.out.println("算术异常!");
        }
    }
}

tip:

IDEA 能自动检查我们的代码风格, 并给出一些更好的建议. 如我们之前写的代码, 在 try 上有一个 "加深底色" , 这时 IDEA 针对我们的

代码提出了一些更好的建议此时把光标放在 try 上悬停, 会给出原因. 按下 alt + enter, 会弹出一个改进方案的弹窗. 我们选择其中的

replace with 'try' with resources此时我们的代码就自动被 IDEA 调整成上面的样子

(7)异常会沿着异常的信息调用栈进行传递

public class TestDemo {
    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) {
            e.printStackTrace();
        }
    System.out.println("after try catch");
    }
}

编译并运行该代码,输出如下:

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

3.异常处理流程

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

4.抛出异常

除了 Java 内置的类会抛出一些异常之外 , 程序猿也可以手动抛出某个异常 . 使用 throw 关键字完成这个操作、
public class TestDemo {
    public static int divide(int x, int y) {
        if (y == 0) {
            throw new ArithmeticException("抛出除 0 异常");
            //我们可以根据实际情况来抛出需要的异常. 在构造异常对象同时可以指定一些描述性信息
        }
        return x / y;
    }
    public static void main(String[] args) {
        System.out.println(divide(10, 0));
    }
}

5.异常说明

我们在处理异常的时候 , 通常希望知道这段代码中究竟会出现哪些可能的异常 . 我们可以使用 throws 关键字 , 把可能抛出的异常显式的标注在方法定义的位置 . 从而提醒调用者要注意捕获这些异常
如:上面的代码可以写成这样
public class TestDemo {
    public static int divide(int x, int y) throws ArithmeticException {
        if (y == 0) {
            throw new ArithmeticException("抛出除 0 异常");
            //我们可以根据实际情况来抛出需要的异常. 在构造异常对象同时可以指定一些描述性信息
        }
        return x / y;
    }
    public static void main(String[] args) {
        System.out.println(divide(10, 0));
    }
}

6.关于finally的注意事项

public class TestDemo {
    public static int func() {
        try {
            return 10;
        }catch(ArithmeticException e){
            e.printStackTrace();
        }finally{
            return 20;
        }
    }
    public static void main(String[] args) {
        System.out.println(func());
    }
}

编译并运行该代码,输出如下:

20

finally 执行的时机是在方法返回之前 (try 或者 catch 中如果有 return 会在这个 return 之前执行 finally). 但是如果finally 中也存在 return 语句 , 那么就会执行 fifinally 中的 return, 从而不会执行到 try 中原有的 return. 一般我们不建议在 fifinally 中写 return ( 被编译器当做一个警告 ).

四、Java异常体系

下图表示 Java 内置的异常类之间的继承关系 :

  • 顶层类 Throwable 派生出两个重要的子类, Error Exception
  • 其中 Error 指的是 Java 运行时内部错误和资源耗尽错误. 应用程序不抛出此类异常. 这种内部错误一旦出现, 除了告知用户并使程序终止之外, 再无能无力. 这种情况很少出现.
  • Exception 是我们程序猿所使用的异常类的父类.
  • 其中 Exception 有一个子类称为 RuntimeException , 这里面又派生出很多我们常见的异常类NullPointerException ,IndexOutOfBoundsException
  • Java 语言规范将派生于 Error 类或 RuntimeException 类的所有异常称为 非受查异常 , 所有的其他异常称为 受查 异常
如果一段代码可能抛出 受查异常 , 那么必须显式进行处理,如:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class TestDemo {
    public static String readFile() {
        // 尝试打开文件, 并读其中的一行.
        File file = new File("d:/test.txt");
        // 使用文件对象构造 Scanner 对象.
        Scanner sc = new Scanner(file);
        return sc.nextLine();
    }
    public static void main(String[] args) {
        System.out.println(readFile());
    }
}

编译并运行该代码,输出如下: 

编译出错了,显式处理的方式有两种:

(1)在方法上加上异常说明, 相当于将处理动作交给上级调用者  

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class TestDemo {
    public static String readFile() throws FileNotFoundException {
        // 尝试打开文件, 并读其中的一行.
        File file = new File("d:/test.txt");
        // 使用文件对象构造 Scanner 对象.
        Scanner sc = new Scanner(file);
        return sc.nextLine();
    }
    public static void main(String[] args) throws FileNotFoundException {
        System.out.println(readFile());
    }
}

(2)使用 try catch 包裹起来 

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class TestDemo {
    public static String readFile(){
        File file = new File("d:/test.txt");
        Scanner sc = null;
        try {
            sc = new Scanner(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return sc.nextLine();
    }
    public static void main(String[] args) {
        System.out.println(readFile());
    }
}

五、自定义异常类  

Java 中虽然已经内置了丰富的异常类 , 但是我们实际场景中可能还有一些情况需要我们对异常类进行扩展 , 创建符合我们实际情况的异常
class NameException extends RuntimeException{
    public NameException(String name){
        super(name);
    }
}
class PasswordException extends RuntimeException{
    public PasswordException(String password){
        super(password);
    }
}
public class TestDemo {
    private static final String name = "xiaoxiao";
    private static final String passwords = "123456";

    public static void login(String name,String password) throws NameException,PasswordException{
        if(!TestDemo.name.equals(name)){
            //System.out.println("用户名错误!");
            throw new NameException("用户名错误!");//如果这里括号里什么都不加,上面就不用重写构造方法
        }
        if(!TestDemo.passwords.equals(password)){
            //System.out.println("密码错误!");
            throw new PasswordException("密码错误!");
        }
    }
    public static void main(String[] args) {
        try{
            login("xiaoxiao","12356");
        }catch(NameException e){
            e.printStackTrace();
            System.out.println("用户名错误!");
        }catch(PasswordException e){
            e.printStackTrace();
            System.out.println("密码错误!");
        }
    }
}

编译并运行该代码,输出如下:

 注意:

  • 自定义异常通常会继承自 Exception 或者 RuntimeException
  • 继承自 Exception 的异常默认是受查异常
  • 继承自 RuntimeException 的异常默认是非受查异常.

因此,如果希望写一个检查性异常类,则需要继承 Exception 类;如果你想写一个运行时异常类,那么需要继承 RuntimeException 类 

最后,我们看一条题:

使用while循环建立类似“恢复模型”的异常处理行为,它将不断重复,知道异常不再抛出

public class TestDemo {
    public static void main(String[] args) {
        int i = 0;
        while(i < 10){
            try{
                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("尝试连接网络第"+i+"次......");
                i++;
            }
        }
        System.out.println("终于有网了!");
    }
}

 编译并运行该代码,输出如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值