异常
1. 认识异常
异常示例:除以0
System.out.println(10/0);
//执行结果
Exception in thread "main" java.lang.ArithmeticException: / by zero
数组下标越界
int [] array = {1,2,3};
System.out.println(arr[5]);
//执行结果
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
访问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
所以,所谓异常指的就是程序在运行时出现错误时通知调用者的一种机制
有些错误时编译时写错的,比如将System.out.println 写成了system.out.println 此时编译过程中就会出错,这就是编译期错误
而运行时错误指的是程序已经编译通过得到了class文件了,再由JVM执行过程中出现的错误
防御式编程
错误在代码中是客观存在的. 因此我们要让程序出现问题的时候及时通知程序猿. 我们有两种主要的方式
LBYL: Look Before You Leap. 在操作之前就做充分的检查.
EAFP: It’s Easier to Ask Forgiveness than Permission. “事后获取原谅比事前获取许可更容易”. 也就是先操作, 遇到问题再处理
异常的核心思想就是 EAFP
2. 异常的基本用法
2.1 捕获异常
基本用法
try{
有可能出现异常的语句 ;
}catch (异常类型 异常对象) {
} ...
finally {
异常的出口
}
- try代码块中放的时可能出现异常的代码
- catch代码块中放的时出现异常后的处理行为
- finally代码块中的代码用于处理善后工作,会在最后执行
- finally可以根据情况选择加或者不加
代码示例1:不处理异常
int[] arr = {1, 2, 3};
System.out.println("before");
System.out.println(arr[5]);
System.out.println("after");
// 执行结果
before
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
一旦出现异常,程序就终止了,after没有输出
代码示例2:使用try catch
int[] arr = {1, 2, 3};
try {
System.out.println("before");
System.out.println(arr[5]);
System.out.println("after");
} catch (ArrayIndexOutOfBoundsException e) {
// 打印出现异常的调用栈
e.printStackTrace();
}
System.out.println("after try catch");
// 执行结果
before
java.lang.ArrayIndexOutOfBoundsException: 5
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[5]);
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 代码块.
如果多个异常的处理方式是完全相同, 也可以写成这样
try{
...
}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表示最后的善后工作,例如释放资源
Scanner scanner = new Scanner(System.in);
try {
int n = scanner.nextInt();
System.out.println(10 / n);
} catch (InputMismatchException e) {
e.printStackTrace();
System.out.println("输入有误");
}catch (ArithmeticException e){
e.printStackTrace();
System.out.println("算数异常,可能0作为除数");
}finally {
//一般用作资源的关闭 无论有没有发生异常,有没有捕获异常,finally都会执行
scanner.close();
System.out.println("finally执行了");
}
代码示例7:使用try负责回收资源
try(Scanner scanner = new Scanner(System.in)) {
int n = scanner.nextInt();
System.out.println(10 / n);
} catch (InputMismatchException e) {
e.printStackTrace();
System.out.println("输入有误");
}catch (ArithmeticException e){
e.printStackTrace();
System.out.println("算数异常,可能0作为除数");
}finally {
//一般用作资源的关闭 无论有没有发生异常,有没有捕获异常,finally都会执行
scanner.close();
System.out.println("finally执行了");
}
将 Scanner 对象在 try 的 ( ) 中创建, 就能保证在 try 执行完毕后自动调用 Scanner
的 close 方法.
代码示例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[5]);
}
// 直接结果
java.lang.ArrayIndexOutOfBoundsException: 5
at demo02.Test.func(Test.java:18)
at demo02.Test.main(Test.java:9)
after try catch
代码示例9: 如果向上一直传递都没有合适的方法处理异常, 最终就会交给 JVM 处理, 程序就会异常终止
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[5]);
}
// 执行结果
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at demo02.Test.func(Test.java:14)
at demo02.Test.main(Test.java:8)
可以看到, 程序已经异常终止了, 没有执行到 System.out.println(“after try catch”); 这一行
2.2 异常处理流程
- 程序先执行try中的代码
- 如果try中的代码出现异常,就会结束try中的代码,检查和catch中得到异常类型是否匹配
- 如果找到匹配的异常类型,就会执行catch中的代码
- 如果没有找到匹配的异常类型,就会将异常向上传递到上层调用者
- 无论是否找到匹配的异常类型,finally中的代码都会被执行(在该方法结束之前执行)
- 如果上层调用者也没有处理异常,就会继续向上传递
- 一直到main方法也没有合适的代码处理异常,就会交给JVM进行处理,此时程序就会异常终止
2.3 抛出异常
程序猿可以手动抛出某个异常,使用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)
2.4 声明异常
处理异常时,通常希望知道这段代码中究竟会出现哪些可能的异常,可以使用throws关键字,把可能抛出的异常显式的标注在方法定义的位置, 从而提醒调用者要注意捕获这些异常.
public static int divide(int x, int y) throws ArithmeticException {
if (y == 0) {
throw new ArithmeticException("抛出除 0 异常");
}
return x / y;
}
2.5 关于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
3. Java异常体系
Java内置的异常类之间的继承关系
- 顶层类 Throwable 派生出两个重要的子类, Error 和 Exception
- 其中 Error 指的是 Java 运行时内部错误和资源耗尽错误. 应用程序不抛出此类异常. 这种内部错误一旦出现,除了告知用户并使程序终止之外, 再无能无力. 这种情况很少出现.
- Exception 是我们程序猿所使用的异常类的父类.
- 其中 Exception 有一个子类称为 RuntimeException , 这里面又派生出很多我们常见的异常类
NullPointerException , IndexOutOfBoundsException 等.
Java语言规范将派生于 Error 类或 RuntimeException 类的所有异常称为 非受查异常, 所有的其他异常称为 受查异常.
如果一段代码可能抛出 受查异常, 那么必须显式进行处理
//受查异常
class MyException extends Exception{
public MyException(String message){
super(message);
}
}
//非受查异常
class MyException1 extends RuntimeException{
public MyException1(String message){
super(message);
}
}
public class Test{
//受查异常显式处理的方式 1:使用 try catch 包裹起来
public static void func(int x){
try {
if (x == 0) {
throw new MyException("hh");
}
}catch (MyException e) {
e.printStackTrace();
}
}
// 受查异常显式处理的方式 2:在方法上加上异常说明, 相当于将处理动作交给上级调用者
public static void func1(int x) throws MyException {
if(x == 0){
throw new MyException("hhhh");
}
}
//非受查异常 如果不用try catch处理 ,在运行的时候 交由JVM处理,直接中断程序
public static void func2(int x)throws MyException1{
try {
if(x == 0){
throw new MyException1("非受查异常");
}
}catch(MyException1 e){
e.printStackTrace();
}
}
4. 自定义异常类
class NameException extends RuntimeException{
public NameException(String message){
super(message);
}
}
class PasswordException extends RuntimeException{
public PasswordException(String message){
super(message);
}
}
public class Test {
private static final String name = "hello";
private static final String password = "123";
public static void login(String name ,String password) throws NameException,PasswordException{
if(!Test1.name.equals(name)){
throw new NameException("用户名错误");
}
if(!Test1.password.equals(password)){
throw new PasswordException("密码错误");
}
}
public static void main(String[] args) {
try{
login("bit","123");
}catch (NameException e){
e.printStackTrace();
System.out.println("用户名错误");
}catch (PasswordException e){
e.printStackTrace();
System.out.println("密码错误");
}finally {
System.out.println("finally执行");
}
}
}
注意事项
- 自定义异常通常会继承自 Exception 或者 RuntimeException
- 继承自 Exception 的异常默认是受查异常
- 继承自 RuntimeException 的异常默认是非受查异常.