Java中什么是异常?
异常通常指的是可能是你的代码在编译的时候没有任何错误,但是在运行时会出现一些异常。也可能是一些无法预料到的异常。
有些错误是这样的, 例如将 System.out.println 拼写错了, 写成system.out.println. 此时编译过程中就会出 错, 这是 “编译期” 出错.而运行时指的是程序已经编译通过得到 class 文件了, 再由 JVM 执行过程中出现的错误.
异常的种类有很多, 不同种类的异常具有不同的含义, 也有不同的处理方式.
我们写代码会遇到各种各样的异常,比较常见的有以下几种异常:
除以0
System.out.println(10 / 0);
//执行结果
Exception in thread "main" java.lang.ArithmeticException: / by zero
数组下标越界
int[] arr = {1, 2, 3, 4};
System.out.println(arr[4]);
//执行结果
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
访问null
public class Test {
public int num = 10;
public static void main(String[] args) {
Test test = null;
System.out.println(test.num);
}
}
//执行结果
Exception in thread "main" java.lang.NullPointerException
异常的基本语法
try {
可能出现异常的代码语句;
} catch (异常的类型 异常的对象) {
处理异常的代码;
} finally {
异常的出口;
}
**注意⚠️:**一旦 try 中出现异常, 那么 try 代码块中的程序就不会继续执行, 而是交给 catch 中的代码来执行. catch 执行完毕会继续往下执行.而且 finally 中的代码一定都会执行到,所以不建议在 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)