07-异常处理

07—异常处理

1. 异常概述与异常体系结构

​ 异常:在Java语言中,将程序执行中发生的不正常情况称为“异常” 。 (开发过程中的语法错误和逻辑错误不是异常)。Java程序在执行过程中所发生的异常事件可分为两类:

  1. Error:Java虚拟机无法解决的严重问题。如:JVM系统内部错误、资源耗尽等严重情况。比如:StackOverflowError和OOM。一般不编写针对性 的代码进行处理。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    public class Error {
    public static void main(String[] args) {
    //1.栈溢出:java.lang.StackOverflowError
    // main(args);

    //2.堆溢出:java.lang.OutOfMemoryError
    // Integer[] arr = new Integer[1024*1024*1024];
    }
    }
  2. Exception: 其它因编程错误或偶然的外在因素导致的一般性问题,可以使 用针对性的代码进行处理。例如:

    1. 空指针访问
    2. 试图读取不存在的文件
    3. 网络连接中断
    4. 数组角标越界

​ 对于这些错误,一般有两种解决方法:一是遇到错误就终止程序的运行。另一种方法是由程序员在编写程序时,就考虑到错误的检测、错误消息的提示,以及错误的处理。捕获错误最理想的是在编译期间,但有的错误只有在运行时才会发生。 比如:除数为0,数组下标越界等

​ 分类:编译时异常和运行时异常

屏幕截图 2021-08-16 082835

  • 运行时异常
    • 是指编译器不要求强制处置的异常。一般是指编程时的逻辑错误,是程序员应该积极避免其出现的异常。java.lang.RuntimeException类及它的子类都是运行时异常。
    • 对于这类异常,可以不作处理,因为这类异常很普遍,若全处理可能会对 程序的可读性和运行效率产生影响。
  • 编译时异常
    • 是指编译器要求必须处置的异常。即程序在运行时由于外界因素造成的一 般性异常。编译器要求Java程序必须捕获或声明所有编译时异常。
    • 对于这类异常,如果程序不处理,可能会带来意想不到的结果。

2. 常见异常

异常体系结构
java.lang.Throwable
|—–java.lang.Error:一般不编写针对性代码进行处理
|—–java.lang.Exception:可以进行异常处理
|—–编译时异常(checked)
|—–IOException
|—–FileNotFoundException
|—–ClassNotFoundException
|—–运行时异常(unchecked)
|—–NullPointerException
|—–ArrayIndexOutOfBoundsException
|—–ClassCastException
|—–NumberFormatException
|—–InputMismatchException
|—–ArithmeticException

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package 异常概述;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.Scanner;

public class ExceptionTest {
//********************以下是运行时异常*************************

//NullPointerException
@Test
public void test1(){
int[] arr = null;
System.out.println(arr[2]);
}

//ArrayINdexOUtofBOundsException
@Test
public void test2(){
int[] arr = new int[10];
System.out.println(arr[10]);
}

//ClassCastException
@Test
public void test3(){
Object obj = new Date();
String str = (String)obj;
}

//NUmberFormanException
@Test
public void test4(){
String str = "abc";
int num = Integer.parseInt(str);

//知识串联:包装类转化为String
//Integer integer = 99;
// String string = String.valueOf(integer);
//System.out.println(string);
}

//InputMismatchException
@Test
public void test5(){
System.out.println("请输入");
Scanner scanner = new Scanner(System.in);
int score = scanner.nextInt();
System.out.println(score);
scanner.close();
}

//ArithmeticException
@Test
public void test6(){
int a = 10;
int b = 0;
System.out.println(a/b);
}

//********************以下是编译时异常*************************
@Test
public void test7(){
File file = new File("hello.txt");
FileInputStream fis = new FileInputStream(file);//Unhandled exception type FileNotFoundexception

int data = fis.read();//Unhandled exception type IOException
while(data != -1){
System.out.println((char) data);
data = fis.read();//Unhandled exception type IOException
}
fis.close();//Unhandled exception type IOException
}
}

3. 异常处理机制一:try-catch-finally

​ 在编写程序时,经常要在可能出现错误的地方加上检测的代码, 如进行x/y运算时,要检测分母为0,数据为空,输入的不是数据 而是字符等。过多的if-else分支会导致程序的代码加长、臃肿, 可读性差。因此采用异常处理机制。
​ Java异常处理 :Java采用的异常处理机制,是将异常处理的程序代码集中在一起, 与正常的程序代码分开,使得程序简洁、优雅,并易于维护。

​ Java提供的是异常处理的抓抛模型。Java程序的执行过程中如出现异常,会生成一个异常类对象, 该异常对象将被提交给Java运行时系统,这个过程称为抛出 (throw)异常。

​ 异常对象的生成:①由虚拟机自动生成:程序运行过程中,虚拟机检测到程序发生了问题,如果在当 前代码中没有找到相应的处理程序,就会在后台自动创建一个对应异常类的实例 对象并抛出——自动抛出;②由开发人员手动创建:Exception exception = new ClassCastException();——创建好的异常对象不抛出对程序没有任何影响,和创建一个普通对象一样

3.1 异常抛出机制

image-20210816084505060

  • 如果一个方法内抛出异常,该异常对象会被抛给调用者方法中处 理。如果异常没有在调用者方法中处理,它继续被抛给这个调用 方法的上层方法。这个过程将一直继续下去,直到异常被处理。 这一过程称为捕获(catch)异常。
  • 如果一个异常回到main()方法,并且main()也不处理,则程序运行终止。
  • 程序员通常只能处理Exception,而对Error无能为力。

异常处理是通过try-catch-finally语句实现的。

1
2
3
4
5
6
7
8
9
10
11
12
try{
...... //可能产生异常的代码
}
catch( ExceptionName1 e ){
...... //当产生ExceptionName1型异常时的处置措施
}
catch( ExceptionName2 e ){
...... //当产生ExceptionName2型异常时的处置措施
}
[ finally{
...... //无论是否发生异常,都无条件执行的语句
} ]
  • try

    捕获异常的第一步是用try{…}语句块选定捕获异常的范围,将可能出现 异常的代码放在try语句块中。

  • catch (Exceptiontype e)

    在catch语句块中是对异常对象进行处理的代码。每个try语句块可以伴随 一个或多个catch语句,用于处理可能产生的不同类型的异常对象。

    如果明确知道产生的是何种异常,可以用该异常类作为catch的参数;也可以用其父类作为catch的参数。 比 如 : 可以 用 ArithmeticException 类 作 为 参 数 的 地 方 , 就 可 以 用 RuntimeException类作为参数,或者用所有异常的父类Exception类作为参数。 但不能是与ArithmeticException类无关的异常,如NullPointerException(catch 中的语句将不会执行)。

    • 捕获异常的有关信息:

      与其它对象一样,可以访问一个异常对象的成员变量或调用它的 方法。

      • getMessage() 获取异常信息,返回字符串

      • printStackTrace() 获取异常类名和异常信息,以及异常出 现在程序中的位置。返回值void。

        屏幕截图 2021-08-16 085000

  • finally

    • 捕获异常的最后一步是通过finally语句为异常处理提供一个统一的出口,使得在控制流转到程序的其它部分以前,能够 对程序的状态作统一的管理。

    • 不论在try代码块中是否发生了异常事件,catch语句是否执行,catch语句是否有异常,catch语句中是否有return, finally块中的语句都会被执行。

    • finally语句和catch语句是任选的

      image-20210816085152978

3.2 不捕获异常时的情况

​ 当异常是RuntimeException类或是它的子类时,这些类的异常的特点是:即使没有使用try和catch捕获,Java自己也能捕获,并且编译通过 ( 但运行时会发生异常使得程序运行终止 )。如果抛出的异常是IOException等类型的非运行时异常,则必须捕获,否则编译错误。也就是说,我们必须处理编译时异常,将异常进行捕捉,转化为运行时异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.io.*;
public class IOExp {
public static void main(String[] args) {
FileInputStream in = new FileInputStream("hello.txt");
int b;
b = in.read();
while (b != -1) {
System.out.print((char) b);
b = in.read();
}
in.close();
}
}

相关知识:FileInputStream类的成员方法read()的功能是每次从相应的(本地为 ASCII码编码格式)文件中读取一个字节,并转换成0~255之间的int型整数返回, 到达文件末尾时则返回-1。

3.3 异常处理示例

image-20210708221213190

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package 异常概述;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/*
一、异常的处理:抓抛模型
过程一:“抛”,程序在正常执行的过程中,一旦出现异常,就会在异常代码出生成一个对应异常类的对象
并将此对象抛出。一旦抛出对象以后,其后的代码就不再执行。

关于异常对象的产生:①系统自动生成的异常对象 ②手动的生成一个异常对象,并抛出(throw)

过程二:“抓”,可以理解为异常的处理方式:①try-catch-finally ②throws

二、try-catch-finally的使用
try{
//可能出现异常的代码
}catch(异常类型1 变量名1){
//处理异常的方式1
}
catch(异常类型2 变量名2){
//处理异常的方式2
}
……
finally{
//一定会执行的代码
}

说明:
1.finally是可选的
2.使用try将可能出现异常的代码包装起来,在执行过程中,一旦出现异常,就会生成一个对应异常的类,根据此对象的类型,去catch中进行匹配
(不会执行发生异常行的后续的且同样被try包括起来的代码)
3.一旦try中的异常对象匹配到某一个catch是,就进入catch中进行异常的处理。一旦处理完成,就跳出当前的try-catch结构(在没有写finally的情况下)。
继续执行其后的代码
4.catch中的异常如果没有子父类关系,则声明的先后顺序对程序无影响
catch中的异常类型如果满足子父类关系,则要求子类一定要声明在父类之前。否则报错
(Exception时NumberFormatException和NullPointerException的父类,所以要声明在二者之后,
而这二者之间无子父类关系,所以二者的先后顺序不做特殊要求)
5.常用的异常对象处理方式:①String getMessage() ②printStackTrace()
6.在try结构中声明的变量,出了try结构以后,就不能再被调用了
7.try-catch-finally结构可以嵌套

体会:
1.使用try-catch-finally处理编译时异常(如test3),使得程序在编译时就不再报错,但是运行时仍可能报错。相当于我们使用try-catch-finally
将一个编译时可能出现的异常,延迟到运行时出现。
2.开发中由于运行时异常比较常见,所以我们通常将不针对运行时异常编写try-catch-finally了。针对编译时的异常,我们要考虑异常的处理。
*/
public class ExceptionTest1 {

@Test
public void test1(){
String str = "abc";
try{
Integer integer = Integer.parseInt(str);
System.out.println("hello-----1");
}catch(NumberFormatException e){
//System.out.println("出现数值转换异常了,不要着急……");
//String getMessage()
System.out.println(e.getMessage());
//printStackTrack
e.printStackTrace();
}catch(NullPointerException e){
System.out.println("出现空指针异常");
}catch(Exception e){
System.out.println("出现异常");
} finally {
System.out.println("执行finally");
}

System.out.println("hello-----2");
}

// @Test
// public void test2(){
// File file = new File("hello.txt");
// FileInputStream fis = null;
// try {
// fis = new FileInputStream(file);
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
//
// int data = 0;
// try {
// data = fis.read();
// } catch (IOException e) {
// e.printStackTrace();
// }
// while(data != -1){
// System.out.println((char) data);
// try {
// data = fis.read();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// try {
// fis.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// }

@Test
public void test3(){
try {
File file = new File("hello.txt");
FileInputStream fis = new FileInputStream(file);//Unhandled exception type FileNotFoundexception

int data = fis.read();//Unhandled exception type IOException
while (data != -1) {
System.out.println((char) data);
data = fis.read();//Unhandled exception type IOException
}
fis.close();//Unhandled exception type IOException
}catch(FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
}

4. 异常处理机制二:throws

声明抛出异常是Java中处理异常的第二种方式

  1. 如果一个方法(中的语句执行时)可能生成某种异常,但是并不能确定如何处理这 种异常,则此方法应显示地声明抛出异常,表明该方法将不对这些异常进行处理, 而由该方法的调用者负责处理。
  2. 在方法声明中用throws语句可以声明抛出异常的列表,throws后面的异常类型可 以是方法中产生的异常类型,也可以是它的父类。

声明抛出异常举例:

1
2
3
4
5
6
public void readFile(String file) throws FileNotFoundException {
……
// 读文件的操作可能产生FileNotFoundException类型的异常
FileInputStream fis = new FileInputStream(file);
..……
}

image-20210816091631721

4.1 重写方法声明抛出异常的原则

重写方法不能抛出比被重写方法范围更大的异常类型。在多态的情况下, 对methodA()方法的调用-异常的捕获按父类声明的异常处理。

1
2
3
4
5
6
7
8
9
10
11
12
public class A {
public void methodA() throws IOException {
……
} }
public class B1 extends A {
public void methodA() throws FileNotFoundException {
……
} }
public class B2 extends A {
public void methodA() throws Exception { //报错
……
} }
4.2 异常处理示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package 异常概述;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/*
三、异常处理方式二 throws + 异常类型
1.“throws + 异常类型”写在方法的声明处。指明此方法执行时,可能会抛出的异常类型。一旦方法体执行时,出现异常,
仍会在异常代码处生成一个异常类的对象,此对象满足throws后异常类型时,就会被抛出
2.体会:try-catch-finally:真正的将异常处理掉。throws的方式只是将异常抛给了调用者。并没真正处理掉
3.开发中如何选择使用try-catch-finaly还是使用throws?
3.1如果父类被重写的方法没有throws方式处理异常,则子类重写的方法也不能使用throws,意味着如果子类重写的方法中有异常,则必须要用try-catch-finally方式处理
3.2执行的方法a中,先后又调用了另外的几个方法,这几个方法是递进关系执行的。我们建议这几个方法使用throws的方式进行处理。而执行的方法a可以考虑使用try-catch-finally方式进行处理
*/
public class ExceptionTest2 {
public static void main(String[] args) {
//method2();//main是静态方法,不能调用非静态的method2()
//此时若main方法也继续往上抛出异常,那么则会抛到虚拟机里。若虚拟机也处理不了,则会崩溃,所以main不建议往上继续抛出
try {
method3();
} catch (IOException e) {
e.printStackTrace();
}

new ExceptionTest2().method2();//method2()已经将异常处理好了,所以不用再继续处理
}
public static void method3() throws IOException{
method1();
}
public void method2(){
try {
method1();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void method1() throws FileNotFoundException, IOException {
File file = new File("hello.txt");
FileInputStream fis = new FileInputStream(file);//Unhandled exception type FileNotFoundexception

int data = fis.read();//Unhandled exception type IOException
while(data != -1){
System.out.println((char) data);
data = fis.read();//Unhandled exception type IOException
}
fis.close();//Unhandled exception type IOException

}
}

5. 手动抛出异常

​ Java异常类对象除在程序执行过程中出现异常时由系统自动生成并 抛出,也可根据需要使用人工创建并抛出。

  1. 首先要生成异常类对象,然后通过throw语句实现抛出操作(提交给Java运 行环境)。 IOException e = new IOException(); throw e;
  2. 可以抛出的异常必须是Throwable或其子类的实例。下面的语句在编译时将会产生语法错误: throw new String(“want to throw”);
5.1 手动抛出异常示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package 手动抛出异常;

public class StudentTest {
public static void main(String[] args) {
try {
Student student = new Student();
student.regist(1001);
System.out.println(student);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

class Student{
private int id;

public void regist(int id) throws Exception {
if(id > 0){
this.id = id;
}else{
throw new Exception("您输入的数据非法");
}
}

@Override
public String toString() {
return "Student{" +
"id=" + id +
'}';
}
}

6. 用户自定义异常类

一般地,用户自定义异常类都是RuntimeException的子类。自定义异常类通常需要编写几个重载的构造器。自定义异常需要提供serialVersionUID,自定义的异常通过throw抛出。自定义异常最重要的是异常类的名字,当异常出现时,可以根据 名字判断异常类型。

image-20210708221744776

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package 用户自定义异常类;
/*
如何自定义异常类?
1.继承于现有的异常结构:RuntimeException、Exception
2.提供全局常量:serialVersionUID
3.提供重载的构造器
*/
public class MyException extends Exception {
static final long serialVersionUID = -7034897193246939L;
public MyException(){

}

public MyException(String msg){
super(msg);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package 用户自定义异常类;
/*
运行时异常向上抛出后不用进行try-catch处理
*/
public class MyRuntimeException extends RuntimeException{
static final long serialVersionUID = -70348971932469399L;

public MyRuntimeException(){

}

public MyRuntimeException(String msg){
super(msg);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package 用户自定义异常类;

public class StudentTest2 {
public static void main(String[] args) {
Student student = new Student();
try {
student.regist(1001);
} catch (MyException e) {
System.out.println(e.getMessage());
}

Stu stu = new Stu();
stu.setId(-111);
}
}

class Student{
private int id;
public void regist(int id) throws MyException {
if(id > 0){
this.id = id;
}else{
throw new MyException("输入的id不能为负");
}
}

@Override
public String toString() {
return "Student{" +
"id=" + id +
'}';
}
}

class Stu{
private int id;
public void setId(int id) {
if(id > 0){
this.id = id;
}else{
throw new MyRuntimeException("输入的id不能为负");
}
}

@Override
public String toString() {
return "Student{" +
"id=" + id +
'}';
}
}

测试题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class ReturnExceptionDemo {
static void methodA() {
try {
System.out.println("进入方法A");
throw new RuntimeException("制造异常");
} finally {
System.out.println("用A方法的finally");
}
}

static void methodB() {
try {
System.out.println("进入方法B");
return;
} finally {
System.out.println("调用B方法的finally");
}
}

public static void main(String[] args) {
try {
methodA();
} catch (Exception e) {
System.out.println(e.getMessage());
}



methodB();
}
}

进入方法A
用A方法的finally
制造异常
进入方法B
调用方法B的finally

image-20210709114937084

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package 异常练习;
/*
* 编写应用程序EcmDef.java,接收命令行的两个参数,要求不能输入负数,计算两数相除。
对数据类型不一致(NumberFormatException)、缺少命令行参数(ArrayIndexOutOfBoundsException、
除0(ArithmeticException)及输入负数(EcDef 自定义的异常)进行异常处理。
提示:
(1)在主类(EcmDef)中定义异常方法(ecm)完成两数相除功能。
(2)在main()方法中使用异常处理语句进行异常处理。
(3)在程序中,自定义对应输入负数的异常类(EcDef)。
(4)运行时接受参数 java EcmDef 20 10 //args[0]=“20” args[1]=“10”
(5)Interger类的static方法parseInt(String s)将s转换成对应的int值。
如:int a=Interger.parseInt(“314”); //a=314;

*/
public class EcmDef {
public static void main(String[] args) {
ecm(args);
}

public static void ecm(String[] args){
try {
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
if(num1 < 0 || num2 < 0){
throw new EcDef("输入不能为负数");
}
System.out.println("两数相除结果为:"+ (num1/num2));
} catch(NumberFormatException e){
e.printStackTrace();
}catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}catch(ArithmeticException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12
package 异常练习;

public class EcDef extends RuntimeException{
static final long serialVersionUID = 1234142134;
public EcDef(){

}

public EcDef(String mes){
super(mes);
}
}

C:\Users\xiong\IdeaProjects\异常\src\异常练习>javac -encoding utf-8 EcmDef.java EcDef.java

C:\Users\xiong\IdeaProjects\异常\src\异常练习>cd ..

C:\Users\xiong\IdeaProjects\异常\src>java 异常练习.EcmDef 20 10
两数相除结果为:2

终端运行时的注意点:

  • 当Java源代码中包含中文字符时,我们在用javac编译时会出现“错误:编码GBK的不可映射字符”。 “输入javac -encoding utf-8 文件名.java。就可以解决了。

  • 找不到或无法加载主类:

    • 方法一:在java文件把包删掉或者注释掉

      image-20210709130129602

    • 方法二:不删除java文件里的package行,返回到package包文件的前一个目录,直接编译。

面试题

throw和throws区别:

throw表示抛出一个异常类的对象,生成异常对象的过程。声明在方法体内。

throws属于异常处理的一种方式,声明在方法的声明处。