你必须了解的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 对象

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

异常的种类有很多, 不同种类的异常具有不同的含义, 也有不同的处理方式

防御式编程

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

LBYL: Look Before You Leap. 在操作之前就做充分的检查.
EAFP: It’s Easier to Ask Forgiveness than Permission. “事后获取原谅比事前获取许可更容易”. 也就是先操作, 遇到 问题再处理.

异常的核心思想就是 EAFP.

异常的基本用法

[]里可写可不写

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

try 代码块中放的是可能出现异常的代码.
catch 代码块中放的是出现异常后的处理行为.
finally 代码块中的代码用于处理善后工作, 会在最后执行.
其中 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

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 (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 类是所有异常类的父类. 因此可以用这个类型表示捕捉所有异常.

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

7.使用 try 负责回收资源

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

自动会执行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[100]);
}
// 直接结果
java.lang.ArrayIndexOutOfBoundsException: 100
 at demo02.Test.func(Test.java:18)
 at demo02.Test.main(Test.java:9)
after try catch
public static void main(String[] args) {
    
    
    func();

异常处理流程

1.程序先执行 try 中的代码
2.如果 try 中的代码出现异常, 就会结束 try 中的代码, 看和 catch 中的异常类型是否匹配.
3.如果找到匹配的异常类型, 就会执行 catch 中的代码
4.如果没有找到匹配的异常类型, 就会将异常向上传递到上层调用者.
5.无论是否找到匹配的异常类型, finally 中的代码都会被执行到(在该方法结束之前执行).
6.如果上层调用者也没有处理的了异常, 就继续向上传递.
7.一直到 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 的注意事项

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.

Java异常体系

在这里插入图片描述
Java语言规范将派生于 Error 类或 RuntimeException 类的所有异常称为 非受查异常, 所有的其他异常称为 受查异常.

如果一段代码可能抛出 受查异常, 那么必须显式进行处理.

public static void main(String[] args) {
    
     
 System.out.println(readFile()); 
} 
public static String readFile() {
    
     
 // 尝试打开文件, 并读其中的一行. 
 File file = new File("d:/test.txt"); 
 // 使用文件对象构造 Scanner 对象. 
 Scanner sc = new Scanner(file); 
 return sc.nextLine(); 
} 
// 编译出错
Error:(13, 22) java: 未报告的异常错误java.io.FileNotFoundException; 必须对其进行捕获或声明以便抛出

如果不显式处理, 编译无法通过.
显式处理的方式有两种:
a) 使用 try catch

public static void main(String[] args) {
    
     
 	System.out.println(readFile()); 
} 
public static String readFile() {
    
     
 	File file = new File("d:/test.txt"); 
 	Scanner sc = null; 
 	try {
    
     
 		sc = new Scanner(file); 
 	} catch (FileNotFoundException e) {
    
     
 		e.printStackTrace(); 
 	} 
 	return sc.nextLine(); 
} 

b) 在方法上加上异常说明, 相当于将处理动作交给上级调用者

public static void main(String[] args) {
    
     
 	try {
    
     
 		System.out.println(readFile()); 
 	} catch (FileNotFoundException e) {
    
     
		e.printStackTrace(); 
 	} 
} 
public static String readFile() throws FileNotFoundException {
    
     
 	File file = new File("d:/test.txt"); 
 	Scanner sc = new Scanner(file); 
 	return sc.nextLine(); 
}

猜你喜欢

转载自blog.csdn.net/Hedenghui777/article/details/121640726