异常处理 - 图1

概述

Java 的异常是 class 下面的图表示了 Java 异常 的家族体系
image.png

可以看到,所有的异常都是继承于 Throwable 类, 分为两大派系,一个是 Error ,一个是 Exception , 其中 Error 表示我们无能为力的错误,这部分我们不用管,我们需要捕捉的是 Exception ,当然 Exception 又分为两类, RuntimeException 的异常 和 非 **RuntimeException** 的异常

其区别:
非 RunTimeException ,受检查异常。必须要开发者解决以后才能编译通过,一般使用其子类,也就是 Java 内部已经帮你想好的,你需要解决的一些常见的异常, 解决的方法有两种:
1:throw到上层,
2,try-catch处理。

RunTimeException :运行时异常,又称不受检查异常,因为不受检查,所以在代码中可能会有 RunTimeException 时Java编译检查时不会告诉你有这个异常,但是在实际运行代码时则会暴露出来,比如经典的1/0,空指针等。 通常用于我们自定义异常的时候做为父类,也就是一些业务逻辑异常。

捕获异常

我们一般使用 try...catch 进行捕获异常,格式如下

  1. try{
  2. ...
  3. }catch(IOException e){
  4. ...
  5. }catch(FileNotFoundException e){
  6. ...
  7. }finally{
  8. ...
  9. }

抛出异常

有些异常我们不知道如何处理,我们可以先往上层抛,等到真正调用的时候再处理。这里我们使用 throws 来抛出异常

  1. import java.io.BufferedReader;
  2. import java.io.FileReader;
  3. import java.io.IOException;
  4. public class ExceptionTest {
  5. public static void main(String[] args) {
  6. // java.io.FileNotFoundException: test.log (The system cannot find the file specified)
  7. // 输出 don't have this file
  8. try{
  9. readFile("test.log");
  10. }catch (IOException e){
  11. //e.printStackTrace();
  12. System.out.println("don't have this file");
  13. }
  14. }
  15. public static void readFile(String fileName) throws IOException {
  16. BufferedReader in = new BufferedReader(new FileReader(fileName));
  17. String str;
  18. while ((str = in.readLine()) != null) {
  19. System.out.println(str);
  20. }
  21. System.out.println(str);
  22. }
  23. }

自定义异常

我们定义业务异常的时候,一般选择从 RuntimeException 里面派生出一个类,然后所有的业务异常继承这个类

  1. public class CustomRuntimeException {
  2. public static void main(String[] args) {
  3. try{
  4. // 如何用?
  5. Business b = new Business();
  6. b.test();
  7. /*
  8. *
  9. * 业务逻辑异常
  10. * BussinessException: 业务逻辑出现异常
  11. * at Business.test(CustomRuntimeException.java:35)
  12. * at CustomRuntimeException.main(CustomRuntimeException.java:12)
  13. *
  14. *
  15. * */
  16. }catch (BussinessException e){
  17. e.printStackTrace();
  18. }
  19. }
  20. }
  21. class BaseException extends RuntimeException{
  22. public BaseException(String msg) {
  23. super(msg);
  24. }
  25. }
  26. class BussinessException extends BaseException{
  27. public BussinessException(String msg){
  28. super(msg);
  29. System.out.println("业务逻辑异常");
  30. }
  31. }
  32. // 新建一个使用的类
  33. class Business{
  34. public void test(){
  35. throw new BussinessException("业务逻辑出现异常");
  36. }