深度分析:Java中如何如理异常,一篇帮你搞定!

异常的背景

初识异常

咱们曾经的代码中已经接触了一些 “异常” 了. 例如:java

除以 0编程

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 对象ide

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

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

防护式编程

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

LBYL: Look Before You Leap. 在操做以前就作充分的检查.
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 (载入游戏画面异常) {
 处理载入游戏画面异常;
}

对比两种不一样风格的代码, 咱们能够发现, 使用第一种方式, 正常流程和错误处理流程代码混在一块儿, 代码总体显的比较混乱. 而第二种方式正常流程和错误流程是分离开的, 更容易理解代码

异常的基本用法

捕获异常
基本语法

try{
 有可能出现异常的语句 ;
}[catch (异常类型 异常对象) {
} ... ]
[finally {
 异常的出口
}]

1.try 代码块中放的是可能出现异常的代码.
2.catch 代码块中放的是出现异常后的处理行为.
3.finally 代码块中的代码用于处理善后工做, 会在最后执行.
4.其中 catch 和 finally 均可以根据状况选择加或者不加.
代码示例1 不处理异常

int[] arr = {1, 2, 3};
System.out.println("before");
System.out.println(arr[100]);
System.out.println("after");
// 执行结果
before
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100

咱们发现一旦出现异常, 程序就终止了. after 没有正确输出.

代码示例2 使用 try catch 后的程序执行过程

int[] arr = {1, 2, 3};
try {
    System.out.println("before");
    System.out.println(arr[100]);
    System.out.println("after");
} catch (ArrayIndexOutOfBoundsException e) {
    // 打印出现异常的调用栈
    e.printStackTrace();
}
System.out.println("after try catch");
// 执行结果
before
java.lang.ArrayIndexOutOfBoundsException: 100
 at demo02.Test.main(Test.java:10)
after try catch

咱们发现, 一旦 try 中出现异常, 那么 try 代码块中的程序就不会继续执行, 而是交给 catch 中的代码来执行. catch 执行完毕会继续往下执行.

代码示例3 catch 只能处理对应种类的异常
咱们修改了代码, 让代码抛出的是空指针异常.

int[] arr = {1, 2, 3};
try {
    System.out.println("before");
    arr = null;
    System.out.println(arr[100]);
    System.out.println("after");
} catch (ArrayIndexOutOfBoundsException e) {
    e.printStackTrace();
}
System.out.println("after try catch");
// 执行结果
before
Exception in thread "main" java.lang.NullPointerException
 at demo02.Test.main(Test.java:11)

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

代码示例4 catch 能够有多个

int[] arr = {1, 2, 3};
try {
    System.out.println("before");
    arr = null;
    System.out.println(arr[100]);
    System.out.println("after");
} catch (ArrayIndexOutOfBoundsExceptione) {
 System.out.println("这是个数组下标越界异常");
    e.printStackTrace();
} catch (NullPointerException e) {
 System.out.println("这是个空指针异常");
    e.printStackTrace();
}
System.out.println("after try catch");
// 执行结果
before
这是个空指针异常
java.lang.NullPointerException
 at demo02.Test.main(Test.java:12)
after try catch

一段代码可能会抛出多种不一样的异常, 不一样的异常有不一样的处理方式. 所以能够搭配多个 catch 代码块.若是多个异常的处理方式是彻底相同, 也能够写成这样

catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
 ...
}

代码示例5 也能够用一个 catch 捕获全部异常(不推荐)

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");
// 执行结果
before
java.lang.NullPointerException
 at demo02.Test.main(Test.java:12)
after try catch

代码示例6 finally 表示最后的善后工做, 例如释放资源

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();
} finally {
    System.out.println("finally code");
}
// 执行结果
before
java.lang.NullPointerException
 at demo02.Test.main(Test.java:12)
finally code

不管是否存在异常, finally 中的代码必定都会执行到. 保证最终必定会执行到 Scanner 的 close 方法

代码示例7 使用 try 负责回收资源
刚才的代码能够有一种等价写法, 将 Scanner 对象在 try 的 ( ) 中建立, 就能保证在 try 执行完毕后自动调用 Scanner的 close 方法.

try (Scanner sc = new Scanner(System.in)) {
    int num = sc.nextInt();
    System.out.println("num = " + num);
} catch (Exception e) {
    e.printStackTrace();
}

代码示例8 若是本方法中没有合适的处理异常的方式, 就会沿着调用栈向上传递

public static void main(String[] args) {
    try {
        func();
   } catch (ArrayIndexOutOfBoundsException e) {
        e.printStackTrace();
   }
    System.out.println("after try catch");
}
public static void func() {
    int[] arr = {1, 2, 3};
    System.out.println(arr[100]);
}
// 直接结果
java.lang.ArrayIndexOutOfBoundsException: 100
 at demo02.Test.func(Test.java:18)
 at demo02.Test.main(Test.java:9)
after try catch

代码示例9 若是向上一直传递都没有合适的方法处理异常, 最终就会交给 JVM 处理, 程序就会异常终止(和咱们最开始未使用 try catch 时是同样的)

public static void main(String[] args) {
    func();
 System.out.println("after try catch");
}
public static void func() {
    int[] arr = {1, 2, 3};
    System.out.println(arr[100]);
}
// 执行结果
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
 at demo02.Test.func(Test.java:14)
 at demo02.Test.main(Test.java:8)

能够看到, 程序已经异常终止了, 没有执行到System.out.println(“after try catch”); 这一行

异常处理流程

程序先执行 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 中的代码保证必定会执行到. 这也会带来一些麻烦

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.通常咱们不建议在 finally 中写 return (被编译器当作一个警告).

自定义异常类

Java 中虽然已经内置了丰富的异常类, 可是咱们实际场景中可能还有一些状况须要咱们对异常类进行扩展, 建立符合咱们实际状况的异常.
例如, 实现一个用户登录功能

class UserException extends Exception {
    public UserException(String message) {
        super(message);
    }
}

class PasswordException extends Exception {
    public PasswordException(String message) {
        super(message);
    }
}

public class TestDemo3 {
    private static String userName = "admin";
    private static String password = "123456";

    public static void main(String[] args) {
        try {
        login("admin", "123456");
        } catch (UserException userError) {
        userError.printStackTrace();
        } catch (PasswordException  passwordError) {
        passwordError.printStackTrace();
        }
    }

    public static void login(String userName, String password) throws UserException, PasswordException {
        if (!TestDemo3.userName.equals(userName)) {
        throw new UserException("用户名错误");
        }
        if (!TestDemo3.password.equals(password)) {
        throw new PasswordException("密码错误");
    }
    System.out.println("登录成功"); }
}

总结:看完有什么不懂的欢迎在下方留言评论,记得点个赞哦!

相关文章
相关标签/搜索