1.异常的产生过程解析
当运行下面的程序时,程序会产生一个数组索引越界异常 ArrayIndexOfBoundsException。我们通过图解来解析下异常产生的过程。
【示例】异常的产生过程案例
// 工具类
class ArraysTool {
// 根据索引获取数组中对应元素的值
public static int getValue(int[] arr, int index) {
int value = arr[index];
return value;
}
}
// 测试类
public class ExceptionDemo {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
int value = ArraysTool.getValue(arr, 3);
System.out.println(value);
}
}
上述程序执行过程图解:
2.抛出异常(throw)
在编写程序时,我们必须要考虑程序出现问题的情况。比如,在定义方法时,方法需要接受参数。那么,当调用方法使用接受到的参数时,首先需要先对参数数据进行合法的判断,数据若不合法,就应该告诉调用者,传递合法的数据进来。这时需要使用抛出异常的方式来告诉调用者。
在 java 中,提供了一个throw关键字,它用来抛出一个指定的异常对象。那么,抛出一个异常
具体如何操作呢?
-
创建一个异常对象,并封装一些提示信息(信息可以自己编写)。
-
需要将这个异常对象告知给调用者,通过关键字throw 就可以完成。
throw 用在方法内,用来抛出一个异常对象,将这个异常对象传递到调用者处,并结束当前方法的执行。
抛出异常格式:throw new 异常类名(参数列表);
【示例】throw 抛出异常案例
// 工具类
class ArraysTool {
// 根据索引获取数组中对应元素的值
public static int getValue(int[] arr, int index) {
// 判断索引是否合法
if(index < 0 || index >= arr.length) {
// 当索引不合法时,抛出索引不合法异常。
// 这时就会结束当前方法的执行,并将异常告知给调用者
throw new ArrayIndexOutOfBoundsException("索引不合法");
}
int value = arr[index];
return value;
}
}
// 测试类
public class ExceptionDemo {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
// 调用方法,获取数组中指定索引处元素
int value = ArraysTool.getValue(arr, 3);
System.out.println(value);
}
}
如果以上代码的索引不合法,那么就会抛出以下的异常!
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 索引不合法
at com.bjsxt.exceprion.ArraysTool.getValue(ExceptionDemo.java:10)
at com.bjsxt.exceprion.ExceptionDemo.main(ExceptionDemo.java:20)
3.声明异常(throws)
声明:将问题标识出来,报告给调用者。如果方法内通过throw 抛出了编译时异常,而没有捕获处理(稍后讲解该方式),那么必须通过throws关键字进行声明,让调用者去处理。
声明异常格式:修饰符 返回值类型 方法名(参数列表) throws 异常类名1, 异常类名2 … { }
【示例】throws 声明异常案例
//工具类
class ArraysTool {
// 使用throws关键字声明异常,把可能发生的异常报告给调用者。
public static int getValue(int[] arr, int index) throws ArrayIndexOutOfBoundsException {
// 判断索引是否合法
if(index < 0 || index >= arr.length)
throw new ArrayIndexOutOfBoundsException("索引不合法");
// 返回元素值
return arr[index];
}
}
throws用于进行异常类的声明,若该方法可能有多种异常情况产生,那么在throws后面可以写多个异常类,用逗号隔开。
【示例】throws 声明多个异常案例
//工具类
class ArraysTool {
// 使用throws关键字声明异常,把可能发生的异常报告给调用者。
public static int getValue(int[] arr, int index) throws NullPointerException, ArrayIndexOutOfBoundsException {
// 判断arr是否为null
if(null == arr)
throw new NullPointerException("对象arr为null");
// 判断索引是否合法
if(index < 0 || index >= arr.length)
throw new ArrayIndexOutOfBoundsException("索引不合法");
// 返回元素值
return arr[index];
}
}
当程序中出现运行时异常时,方法定义中无需 throws 声明该异常,调用者也无需捕获处理该异常(即没有try-catch),系统会把异常一直默认往上层抛,一直抛到最上层。
当程序中出现非运行时异常时,要么用try-catch语句捕获它,要么用throws语句声明抛出它,否则编译不会通过。
【示例】throws 声明非运行时异常案例
// Demo类
class Demo {
/*
* 因为NullPointerException是运行时异常,可以不用在方法上使用throws声明
* 而FileNotFoundException是非运行时异常,此处应该在方法上使用throws声明,否则编译不通过
*/
public void test(Object obj, String path) throws FileNotFoundException {
// 判断obj是否为null
if(null == obj)
throw new NullPointerException("obj不能为null");
// 创建文件字节读取流对象,如果文件地址不存在会抛出FileNotFoundException异常
FileInputStream is = new FileInputStream(path);
}
}
// 测试类
public class ThrowsExceptionDemo {
/*
* main()方法中没有对FileNotFoundException异常进行捕获处理,那么应该继续在main()方法上抛出,最后交给JVM来做处理
*/
public static void main(String[] args) throws FileNotFoundException {
// 调用Demo类中的test()方法
new Demo().test(new Object(), "D://abc.txt");
}
}
4.捕获异常(try-catch-finally)
如果程序出现了异常,自己又解决不了,那么可以把异常声明出来(throws),报告给调用者,让调用者来做处理。
如果出现的异常自己能解决,那么就不用声明异常,而是自己捕获该异常(try-catch-finally),并在catch块中对该异常做处理。
一个try语句必须带有至少一个catch语句块或一个finally语句块 。
4.1try-catch组合方式
try-catch 组合:对代码进行异常检测,并对检测到的异常传递给 catch 处理。
捕获异常格式:
try {
// 需要被检测的语句。
} catch(异常类 变量) { // 参数
// 异常的处理语句。
}
try:该代码块中编写可能产生异常的代码,该段代码就是一次捕获并处理的范围。在执行过程中,当任意一条语句产生异常时,就会跳过该段中后面的代码。代码中可能会产生并抛出一种或几种类型的异常对象,它后面的catch语句要分别对这些异常做相应的处理。
catch:用来进行某种异常的捕获,实现对捕获到的异常进行处理。catch中的参数就是被捕获到的异常对象(也就是被抛出的那个异常对象),我们可以根据这个异常对象来获取到该异常的具体信息。
【示例】try-catch捕获异常案例
// 工具类
class ArraysTool {
// ArrayIndexOutOfBoundsException属于运行时异常,可以不用强制throws声明
public static int getValue(int[] arr, int index) {
// 判断索引是否合法
if(index < 0 || index >= arr.length) {
throw new ArrayIndexOutOfBoundsException("索引不合法");
}
// 返回元素值
return arr[index];
}
}
// 测试类
public class TryCatchDemo {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
try {
// 获取元素的值,可能会抛出异常对象
// 如果发生了异常,那么就会结束当前当前代码块的执行
int value = ArraysTool.getValue(arr, 5);
System.out.println("value:" + value); // 不执行
} catch(ArrayIndexOutOfBoundsException e) { // 参数被抛出的异常对象
// 获取异常信息
System.out.println("msg:" + e.getMessage());
// 打印异常对象,该对象重写了toString()方法
System.out.println("exception:" + e);
// 输出栈异常
e.printStackTrace();
}
// 无论是否发生异常,该代码都执行
System.out.println("over"); // 执行
}
}
一个 try 多个 catch 组合 : 对代码进行异常检测,并对检测的异常传递给 catch 处理。对每种异常信息进行不同的捕获处理。
// 工具类
class ArraysTool {
public static int getValue(int[] arr, int index) throws Exception {
// 判断arr是否为null
if(null == arr)
throw new NullPointerException("对象arr不能为null");
// 判断索引是否大于等于arr.length
if(index >= arr.length)
throw new ArrayIndexOutOfBoundsException("索引不能大于等于数组长度");
// 判断索引是否小于0
if(index < 0)
throw new Exception("索引不能小于0");
// 返回元素值
return arr[index];
}
}
// 测试类
public class TryCatchDemo {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
try {
// 获取元素的值,可能会抛出异常对象
int value = ArraysTool.getValue(arr, -5);
System.out.println("value:" + value); // 不执行
} catch (NullPointerException e) { // 空指针异常
// 获取异常信息
System.out.println("msg:" + e.getMessage());
// 输出栈异常
e.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e) {// 索引大于等于数组长度异常
// 获取异常信息
System.out.println("msg:" + e.getMessage());
// 输出栈异常
e.printStackTrace();
}
// 多catch的时候,父类异常的catch应该放在最下面!!!
catch (Exception e) { // 索引小于0异常
// 获取异常信息
System.out.println("msg:" + e.getMessage());
// 输出栈异常
e.printStackTrace();
}
// 无论是否发生异常,该代码都执行
System.out.println("over"); // 执行
}
}
注意:这种异常处理方式,要求多个 catch 中的异常不能相同,并且若 catch 中的多个异常之间有子父类异常的关系,那么子类异常要求在上面的 catch 处理,父类异常在下面的 catch 处理。
4.2try-catch-finally组合方式
try-catch-finally组合:检测异常,并传递给 catch 处理,并在 finally 中进行资源释放。
捕获异常格式:
try {
// 需要被检测的语句。
} catch(异常类 变量) { // 参数
// 异常的处理语句。
} finally {
// 一定会被执行的语句,用于释放资源。
}
try:该代码块中编写可能产生异常的代码,该段代码就是一次捕获并处理的范围。
catch:用来进行某种异常的捕获,实现对捕获到的异常进行处理,可以一个key对应多个catch。
finally:有一些特定的代码**无论异常是否发生,都需要执行。**另外,因为异常会引发程序跳转,导致有些语句执行不到。而 finally 就是解决这个问题的,在 finally 代码块中存放的代码都是一定会被执行的。
【示例】try-catch-finally捕获异常案例
// 工具类
class ArraysTool {
public static int getValue(int[] arr, int index) {
// 判断arr是否为null
if(arr == null)
throw new NullPointerException("对象arr不能为null");
// 判断索引是否合法
if(index < 0 || index >= arr.length)
throw new ArrayIndexOutOfBoundsException("索引不合法");
// 返回元素值
return arr[index];
}
}
// 测试类
public class TryCatchDemo {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
try {
// 获取元素的值,可能会抛出异常对象
int value = ArraysTool.getValue(arr, -2);
System.out.println("value:" + value); // 不执行
} catch (NullPointerException e) { // 空指针异常
// 获取异常信息
System.out.println("msg:" + e.getMessage());
// 输出栈异常
e.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e) { // 索引不合法异常
// 获取异常信息
System.out.println("msg:" + e.getMessage());
// 输出栈异常
e.printStackTrace();
} finally {
// 无论异常是否发生,都需要执行finally中的代码。
// finally块中的代码一般用于释放资源。
System.out.println("执行finally");
}
// 无论是否发生异常,该代码都执行
System.out.println("over"); // 执行
}
}
注意:即使在try或catch中添加return,finally中的代码都会执行,除非调用System.exit(0);做退出虚拟机的操作,这样finally中的代码才不会执行。
【示例】在try或catch中添加return案例
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
try {
// 获取元素的值,可能会抛出异常对象
int value = arr[4];
System.out.println("value:" + value);
return; // 添加return;
} catch (ArrayIndexOutOfBoundsException e) {
return; // 添加return;
} finally {
// 在try或catch中添加return操作,finally块中的代码依旧会执行
System.out.println("执行finally"); // 执行
}
}
【示例】在try或catch中添加System.exit(0);案例
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
try {
// 获取元素的值,可能会抛出异常对象
int value = arr[3];
System.out.println("value:" + value);
System.exit(0); // 退出虚拟机操作
} catch (ArrayIndexOutOfBoundsException e) {
System.exit(0); // 退出虚拟机操作
} finally {
// 在try或catch中添加System.exit(0);操作,finally块中的代码才不会执行
System.out.println("不执行finally"); // 不执行
}
}
4.3try-finally组合方式
try-finally 组合: 对代码进行异常检测,检测到异常后因为没有catch,所以一样会被默认 jvm 抛出。异常是没有捕获处理的。但是功能所开启资源需要进行关闭,所有finally只为关闭资源。
捕获异常格式:
try {
// 需要被检测的语句。
} finally {
// 一定会被执行的语句,用于释放资源。
}
【示例】try-finally组合案例
// 抛出Exception异常
public static void main(String[] args) throws Exception {
try {
// 非运行时异常,如果没有用catch捕获,那么应该在方法上声明异常
throw new Exception("自定义异常");
} finally {
// 关闭资源操作。。。
}
}
ps:如需最新的免费文档资料和教学视频,请添加QQ群(627407545)领取。
是没有捕获处理的。但是功能所开启资源需要进行关闭,所有finally只为关闭资源。
捕获异常格式:
try {
// 需要被检测的语句。
} finally {
// 一定会被执行的语句,用于释放资源。
}
【示例】try-finally组合案例
// 抛出Exception异常
public static void main(String[] args) throws Exception {
try {
// 非运行时异常,如果没有用catch捕获,那么应该在方法上声明异常
throw new Exception("自定义异常");
} finally {
// 关闭资源操作。。。
}
}
ps:如需最新的免费文档资料和教学视频,请添加QQ群(627407545)领取。