Java异常

异常

1、了解异常的背景

认识异常
在以前,我们已经认识了一些异常了
例如:
除以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对象

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

2、认识Java异常体系

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

3、异常的基本用法

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

try 代码块中放的是可能出现异常的代码.
catch 代码块中放的是出现异常后的处理行为.
finally 代码块中的代码用于处理善后工作, 会在最后执行.
其中 catchfinally 都可以根据情况选择加或者不加.

通过代码看一下异常的使用:

	用一个 catch 捕获所有异常(不推荐)public static void main(String[] args) {
        int[] array = {1,2,3,4,5,6};
        try (Scanner scanner = new Scanner(System.in)) {
            //array = null;
            //int a = scanner.nextInt();
            System.out.println(array.length);
            System.out.println("before");
            System.out.println(array[3]);
        } catch (Exception e) {   //
            e.printStackTrace();
            System.out.println("异常捕获");
        } finally {
            //资源的关闭-》文件打开-》文件关闭
            System.out.println("finally永远会被执行的!");
        }
        System.out.println("after");
    }
    
代码示例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
代码示例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 执
行完毕会继续往下执行.

关于异常的处理方式
异常的种类有很多, 我们要根据不同的业务场景来决定.
对于比较严重的问题(例如和算钱相关的场景), 应该让程序直接崩溃, 防止造成更严重的后果
对于不太严重的问题(大多数场景), 可以记录错误日志, 并通过监控报警程序及时通知程序猿
对于可能会恢复的问题(和网络相关的场景), 可以尝试进行重试.
在我们当前的代码中采取的是经过简化的第二种方式. 我们记录的错误日志是出现异常的方法调用信息, 能很快
速的让我们找到出现异常的位置. 以后在实际工作中我们会采取更完备的方式来记录异常信息

关于 "调用栈"
方法之间是存在相互调用关系的, 这种调用关系我们可以用 "调用栈" 来描述. 在 JVM 中有一块内存空间称为 "虚
拟机栈" 专门存储方法之间的调用关系. 当代码中出现异常的时候, 我们就可以使用 e.printStackTrace(); 的
方式查看出现异常代码的调用栈

代码示例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 (ArrayIndexOutOfBoundsException e) {
	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

由于 Exception 类是所有异常类的父类. 因此可以用这个类型表示捕捉所有异常

备注: catch 进行类型匹配的时候, 不光会匹配相同类型的异常对象, 也会捕捉目标异常类型的子类对象.
如刚才的代码, NullPointerException 和 ArrayIndexOutOfBoundsException 都是 Exception 的子类, 因此都
能被捕获到.

代码示例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 方法
关于 finally 的注意事项
	public static int func() {
        try {
            int a = 10/0;
            return 88;
        }catch (NullPointerException e) {
            e.printStackTrace();
            System.out.println("算术异常");
            return 8;
        }finally {
            //建议return不要放在finally块当中
            //因为可能会抑制catch或者try当中的return。
            System.out.println("finally");
            //return 9;
        }
    }
    finally{}中的代码永远会被执行的,一般用在资源关闭上
	finally 中的代码一定都会执行到. 保证最终一定会执行到 Scanner 的 close 方法
	return不要放在finally块中
	在finally里面写了returna语句以后,会一直try块和catch块中的return语句

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

代码示例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;
} 

4、自定义异常类

自定义异常在抛出的时候,需要自己进行throws声明,声明了在调用到时候,要用try{}catch{}包起来

自定义异常:大前提要继承Exception

例如, 我们实现一个用户登陆功能.

public class Test {
	 private static String userName = "admin";
 	private static String password = "123456";
 	public static void main(String[] args) {
 		login("admin", "123456");
 	}
 	public static void login(String userName, String password) {
 		if (!Test.userName.equals(userName)) {
 			// TODO 处理用户名错误
 		}
 		if (!Test.password.equals(password)) {
 			// TODO 处理密码错误
 		}
 		System.out.println("登陆成功");
 	}
} 
//此时我们在处理用户名密码错误的时候可能就需要抛出两种异常. 我们可以基于已有的异常类进行扩展(继承), 创建和我们业务相关的异常类
class UserError extends Exception {
 	public UserError(String message) {
 		super(message);
 	}
}
class PasswordError extends Exception {
 	public PasswordError(String message) {
 		super(message);
 	}
} 
//此时我们的 login 代码可以改成
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 {
 	if (!Test.userName.equals(userName)) {
 		throw new UserError("用户名错误");
 	}
 	if (!Test.password.equals(password)) {
 		throw new PasswordError("密码错误");
 	}
 	System.out.println("登陆成功");
} 

注意事项
自定义异常通常会继承自 Exception 或者 RuntimeException
继承自 Exception 的异常默认是受查异常
继承自 RuntimeException 的异常默认是非受查异常.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值