编程过程中遇到异常怎么办?带你详细了解异常

1.JAVA异常体系

体系结构图

Error 类或 RuntimeException 类的所有异常称为非受查异常(蓝色)
所有的其他异常称为受查异常(红色)

  • 顶层类 Throwable 派生出两个重要的子类, Error 和 Exception
  • 其中 Error 指的是 Java 运行时内部错误和资源耗尽错误. 应用程序不抛出此类异常.这种内部错误一旦出现,只能告知用户并使程序终止, 这种情况很少出现.
  • Exception 是我们程序猿所使用的异常类的父类.
  • Exception 有一个子类称为 RuntimeException ,这里面又派生出很多我们常见NullPointerException , IndexOutOfBoundsException 等.

非受查异常

Error 类或 RuntimeException 类的所有异常称为非受查异常(蓝色)
其中 Error 指的是 Java 运行时内部错误和资源耗尽错误. 应用程序不抛出此类异常. 这种内部错误一旦出现,除了告知用户并使程序终止之外, 再无能无力. 这种情况很少出现.

受查异常

所有的其他异常称为受查异常(红色)
如果一段代码可能抛出 受查异常, 那么必须显式处理.

显式处理方式
a) 使用 try catch 包裹起来
public static void main(String[] args) { 
 System.out.println(readFile()); 
} 
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(); 
}
b) 在方法上加上异常说明, 将处理动作交给上级调用者
public static void main(String[] args) { 
 try { 
 System.out.println(readFile()); 
 } catch (FileNotFoundException e) { 
 e.printStackTrace(); 
 } 
} 
public static String readFile() throws FileNotFoundException { 
 File file = new File("d:/test.txt"); 
 Scanner sc = new Scanner(file); 
 return sc.nextLine(); 
}

2.异常的背景

初识异常

所谓异常指的就是程序在运行时出现错误时通知调用者的一种机制

除数为零
System.out.println(10/0);

//运行结果
Exception in thread "main" java.lang.ArithmeticException: / by zero
数组下标越界
int[] arr = {1, 2, 3};
System.out.println(arr[100]);
// 执行结果
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
访问null对象
public class Test {
    public int num = 10;
    public static void main(String[] args) {
        Test t = null;
        System.out.println(t.num);
   }
}
// 执行结果
Exception in thread "main" java.lang.NullPointerException

“编译期” 出错.:如将 System.out.println 拼写错了, 写成了 system.out.println. 此时编译过程中就会出错。
运行时:程序已经编译通过得到 class 文件了, 再由 JVM 执行过程中出现的错误

防御式编程

错误在代码中是客观存在的. 程序出现问题的时候及时通知程序猿有两种主要的方式

  1. LBYL: Look Before You Leap. 在操作之前就做充分的检查.
  2. EAFP: It’s Easier to Ask Forgiveness than Permission.
    “事后获取原谅比事前获取许可更容易”. 也就是先操作, 遇到问题再处理.

异常的好处

LBYL 风格的代码(不使用异常)

boolean ret = false;
ret = 登陆游戏();
if (!ret) {
 处理登陆游戏错误;
    return; 
}
ret = 开始匹配();
if (!ret) {
 处理匹配错误;
    return; 
}
ret = 游戏确认();
if (!ret) {
 处理游戏确认错误;
    return;
}
ret = 选择英雄();
if (!ret) {
    处理选择英雄错误;
    return;
}
ret = 载入游戏画面();
if (!ret) {
 处理载入游戏错误;
    return;
}

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

try {
    登陆游戏();
    开始匹配();
    游戏确认();
    选择英雄();
    载入游戏画面();
   ...
} catch (登陆游戏异常) {
    处理登陆游戏异常;
} catch (开始匹配异常) {
 处理开始匹配异常;
} catch (游戏确认异常) {
 处理游戏确认异常;
} catch (选择英雄异常) {
 处理选择英雄异常;
} catch (载入游戏画面异常) {
 处理载入游戏画面异常; }

对比两种不同风格的代码, 使用第一种方式, 正常流程和错误处理流程代码混在一起, 代码整体显的比较混乱. 而第二种方式正常流程和错误流程是分离开的, 更容易理解代码.

3.异常的用法

捕获异常

基本语法

try{ 
 有可能出现异常的语句 ; 
}[catch (异常类型 异常对象) {
} ... ]
[finally {
 异常的出口
}]
  • try 代码块中放的是可能出现异常的代码.
  • catch 代码块中放的是出现异常后的处理行为.
  • finally代码块中的代码用于处理善后工作, 会在最后执行.
  • 其中 catch 和 finally 都可以根据情况选择加或者不加.

异常处理流程

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

抛出异常

除了 Java 内置的类会抛出一些异常, 程序猿也可以手动抛出某个异常. 使用 throw 关键字完成这个操作.

public static void main(String[] args) { 
 System.out.println(divide(10, 0)); 
} 
public static int divide(int x, int y) { 
 if (y == 0) { 
 throw new ArithmeticException("抛出除 0 异常"); 
 } 
 return x / y; 
} 
// 执行结果
Exception in thread "main" java.lang.ArithmeticException: 抛出除 0 异常
 at demo02.Test.divide(Test.java:14) 
 at demo02.Test.main(Test.java:9)

异常说明

我们在处理异常的时候, 通常希望知道这段代码中究竟会出现哪些可能的异常.我们可以使用 throws 关键字, 把可能抛出的异常显式的标注在方法定义的位置. 从而提醒调用者要注意捕获这些异常

public static int divide(int x, int y) throws ArithmeticException { 
 if (y == 0) { 
 throw new ArithmeticException("抛出除 0 异常"); 
 } 
 return x / y; 
}

finally 的注意事项

finally 执行的时机是在方法返回之前(try 或者 catch 中如果有 return 会在这个 return 之前执行 finally). 但是如果finally 中也存在 return 语句, 那么就会执行 finally 中的 return, 从而不会执行到 try 中原有的 return.(一般不建议finally中加return语句)

public static void main(String[] args) { 
 System.out.println(func()); 
} 
public static int func() { 
 try { 
 return 10; 
 } finally { 
 return 20; 
 } 
} 
// 执行结果
20

4.自定义异常类

Java 中虽然已经内置了丰富的异常类, 但是我们实际场景中可能还有一些情况需要我们对异常类进行扩展, 创建符合我们实际情况的异常.

用户登录异常程序

代码实例
class UserError extends Exception {
    public UserError(String message) {
        super(message);
    }
}
class PasswordError extends Exception {
    public PasswordError(String message) {
        super(message);
    }
}
public class TestDemo {
    private static String userName = "admin" ;
    private static String password = "123456";

    public static void main(String[] args) {
        try {
            login("admin", "123456");
        } catch (UserError userError) {
            userError.printStackTrace();
        } catch (PasswordError passwordError) {
            passwordError.printStackTrace();
        }
    }
    public static void login(String userName, String password) throws UserError, PasswordError {
        System.out.println("欢迎来到登陆界面");
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名");
        userName = scanner.nextLine();
        System.out.println("请输入密码");
        password = scanner.nextLine();
        if (!TestDemo.userName.equals(userName)) {
            throw new UserError("用户名错误");
        }
        if (!TestDemo.password.equals(password)) {
            throw new PasswordError("密码错误");
        }
        System.out.println("登陆成功");
    }
运行结果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值