完成异常处理

master
高宏宇 2 years ago
parent da2166db38
commit 6b25b91075

@ -0,0 +1,448 @@
> When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can continue to run or terminate gracefully? This is the subject we will introduce in this chapter.
## 1. 如何处理异常
### 1.1. 不对异常进行处理
我们先来看看一个除零异常的处理:
```java
import java.util.Scanner;
public class Quotient {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter two integers
System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
System.out.println(number1 + " / " + number2 + " is " + (number1 / number2));
}
}
```
上述代码并没有对除数是0的情况进行特殊的处理如果遇到除数是0的情况程序将产生一个运行时错误。
```java
Enter two integers: 29 0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Quotient.main(Quotient.java:12)
```
显然,这种方式错误的,程序应该保证足够的健壮性。如果出现上述的错误,程序可能被异常终止,这是我们不愿意看到的情况。
### 1.2. 使用简单判断处理异常
为了对该错误进行处理,或者是掌控该错误,不至于使得程序的流程不可控,我们进行了如下改进:
```java
import java.util.Scanner;
public class QuotientWithIf {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter two integers
System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
if (number2 != 0)
System.out.println(number1 + " / " + number2 + " is " + (number1 / number2));
else
System.out.println("Divisor cannot be zero ");
}
}
```
当除数为0的时候程序将给出提示。
### 1.3. 在被调用函数内部处理异常
大多情况下异常可能是因为调用函数引起的例如打开不存在的文件引用变量为null等。那么上面的程序写成函数就成了
```java
import java.util.Scanner;
public class QuotientWithMethod {
public static int quotient(int number1, int number2) {
if (number2 == 0) {
System.out.println("Divisor cannot be zero");
System.exit(1);
}
return number1 / number2;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter two integers
System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
int result = quotient(number1, number2);
System.out.println(number1 + " / " + number2 + " is " + result);
}
}
```
可以看到,`quotient()`函数内部对除数进行了判断,避免产生除零的错误。这样做有很多不好的地方:
1. 函数的调用方应该知道被调用的函数产生了错误,但这个例子中调用方显然不知道。例如打开文件应该让调用方知晓是否成功,以便进行后续的流程;
2. 上述代码可以修改成让主函数对除零的情况进行判断,但这样任然有问题。被调用函数作为一个代码复用单元,应该保证自己代码的健壮性,应该可以处理输入参数的异常,而不应该把这个责任推脱给调用方。
那么如何才及让被调用函数处理异常又让调用方知道发生了什么异常考虑传统C的做法
1. 如果这个被调用函数本身不需要有返回值可以使用返回值来告调用者我出现了什么异常在c中这种方式被广泛使用
2. 如果被调用函数需要有返回值的情况C可以通过全局变量或者通过指针传递参数的方式通知调用方发生了什么异常。
3. 当然还有其他的技术,例如返回复杂结构结构体等等。
java当然可以借鉴C的方式对异常进行处理但是当函数的嵌套调用层次多C的处理方式显然会越来越复杂。
### 1.4. 使用Java的异常处理机制
在Java中或者是很多高级语言当中有一个更高级的异常处理机制叫做异常捕获机制
```java
import java.util.Scanner;
public class QuotientWithException {
public static int quotient(int number1, int number2) {
if (number2 == 0)
throw new ArithmeticException("Divisor cannot be zero");
return number1 / number2;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter two integers
System.out.print("Enter two integers: ");
int number1 = input.nextInt();
int number2 = input.nextInt();
try {
int result = quotient(number1, number2);
System.out.println(number1 + " / " + number2 + " is " + result);
} catch (Exception ex) {
System.out.println("Exception: an integer " + ex.getMessage());
}
System.out.println("Execution continues ...");
}
}
```
1. `quotient()`函数内部,并没有给出除零错误的输出,而是使用 `throw new ArithmeticException("Divisor cannot be zero");`抛出了一个异常对象。
2. 在组函数中,使用 try...catch语法去捕获这个异常并进行相应的处理。
语法上更复杂了,那这么做有什么好处?
Java的异常处理提供了一种不改变函数调用方式而可以获知被调用函数执行异常的一种机制。这样方式在很多情况下是非常有用的。例如大多情况下函数的调用者希望知道函数运行是否正常而不是让被调用函数自己处理。这时需要被调用函数向调用者返回一个数据说明被调用函数遇到了什么异常。好了如果这个被调用函数本身不需要有返回值可以使用返回值来告调用者我出现了什么异常在c中这种方式被广泛使用。但是如果被调用函数需要有返回值应该如何处理当然有很多技术例如在C中可以通过全局变量或者通过指针传递参数的方式。但这些方式都是对被调用函数的**入侵**,要不改变函数参数,要不需要被调用函数修改全局变量。函数就是函数,输入参数,计算结果;如果有异常,最好通过一种专门而通用的方式告知函数调用方,而不改变函数的签名。
异常处理就是为了解决上面的问题,虽然看样子好像复杂了,但是给出了一种不改变函数签名的一种通用异常通知手段。这种方式对程序的结构非常有帮助。另外一个原因就是异常处理是面向对象的方式,可以用多态的方式处理复杂的异常情况。
### 1.5. 输入类型不匹配的异常
```java
import java.util.*;
public class InputMismatchExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
// Display the result
System.out.println("The number entered is " + number);
continueInput = false;
} catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine(); // discard input
}
} while (continueInput);
}
}
```
上述代码中`int number = input.nextInt();`是从控制台读取一个整形但是如果控制台输入的不是整形如何处理Scanner的`nextInt()`函数当遇到问题的时候会抛出一个异常,这个异常可以被调用方捕获到。
这里使用了try...catch的语法
1. try语法块是你需要运行的代码且这些代码可能会产生异常
2. 当try块中的代码抛出了异常程序会立即进入到 catch 语法块且catch后面的参数携带了一个被抛出的异常对象该对象有异常发生时的全部信息调用栈异常描述等等
3. cache块可以通过这个异常对象上述是ex这个对象对异常进行处理。
这就是基本的异常处理。
## 2. 异常的分类
接下来进一步理解异常。前面例子抛出异常的时候使用了new 这个关键字构造一个异常对象。异常是对象,它的继承关系如下图:
![image-20230319220051352](img/image-20230319220051352.png)
可以看到所有的异常类都由Throwable扩展而来Throwable由Object扩展而来然后分成了两个大的分支Exception和Error。
### 2.1. 系统错误
> System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully.
>
> 系统错误(Error)是由JVMJava虚拟机抛出的这个错误描述了Java系统内部的错误这种错误非常少发生一旦发生你几乎没有什么可以做的除了通知用户优雅的终止程序。
该类错误最致命预示着你的JAVA虚拟机系统崩溃了这种情况下你什么也做不了。
### 2.2. 异常
> Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.
>
> 异常Exception是有程序和外部条件引起的你的程序可以通过代码对该类错误进行处理。
### 2.3. 运行时异常
> RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.
>
> 运行时异常RuntimeException是程序运行中的错误废话如类型转换错误数组下标越界等。
### 2.4. Checked 和 Unchecked 异常
> RuntimeException, Error and their subclasses are known as unchecked exceptions. All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with the exceptions.
>
> 运行时异常(RuntimeException),系统错误(Error),以及这两类的子类叫做**非检查异常**unchecked exceptions其他的错误类型是**检查异常**意味着编程人员需要捕获和处理这些异常调用这些函数必须使用trycache语法块或者是重新再抛出否则编译器会报错。
## 3. 异常处理
![image-20230321085805652](img/image-20230321085805652.png)
异常处理包括:
1. 声明异常(被调用函数中)
2. 抛出异常(被调用函数中)
3. 异常捕获(调用函数)
### 3.1. 定义异常
> Every method must state the types of checked exceptions it might throw. This is known as declaring exceptions.
>
> 所有标识了**异常**的函数都可能抛出异常,这就是异常的声明。
```java
public void myMethod()
throws IOException
public void myMethod()
throws IOException, OtherException
```
定义异常在函数最后面,函数体大括号之前。
### 3.2. 抛出异常
> When the program detects an error, the program can create an instance of an appropriate exception type and throw it. This is known as throwing an exception. Here is an example:
>
> 当函数检查到错误可以生成一个异常的实例对象然后使用throw操作抛出这个异常对象这个异常对象将被调用函数处理。
```java
throw new TheException();
TheException ex = new TheException();
throw ex;
```
例如,当设置圆的半径的时候,需要半径不为负数:
```java
public void setRadius(double newRadius) throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException("Radius cannot be negative");
}
```
### 3.3. 异常捕获
异常捕获的语法是:
```java
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}
```
try后面的大括号所包含的代码块中是可能抛出异常的函数调用catch语法块后面是异常引用变量有异常类型表示如何处理该类异常当然try语法块中函数可能抛出不同类型的异常因此可以有多个catch语法块。
**注意:异常对象类的实例,因此你可以用一个`catch (Exception exp){...}`来处理几乎所有的异常这也是多态的应用。另外catch 语法块后面的参数类型只能接受`Throwable`和其子类。**
### 3.4. 完整的例子
这里例子当圆的半径小于零将抛出异常:
```java
public class CircleWithException {
/** The radius of the circle */
private double radius;
/** The number of the objects created */
private static int numberOfObjects = 0;
/** Construct a circle with radius 1 */
public CircleWithException() {
this(1.0);
}
/** Construct a circle with a specified radius */
public CircleWithException(double newRadius) {
setRadius(newRadius);
numberOfObjects++;
}
/** Return radius */
public double getRadius() {
return radius;
}
/** Set a new radius */
public void setRadius(double newRadius) throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException("Radius cannot be negative");
}
/** Return numberOfObjects */
public static int getNumberOfObjects() {
return numberOfObjects;
}
/** Return the area of this circle */
public double findArea() {
return radius * radius * 3.14159;
}
}
```
注意:`setRadius(double newRadius) `函数头定义了抛出异常`throws IllegalArgumentException`。
调用函数:
```java
public class TestCircleWithException {
public static void main(String[] args) {
try {
CircleWithException c1 = new CircleWithException(5);
CircleWithException c2 = new CircleWithException(-5);
CircleWithException c3 = new CircleWithException(0);
} catch (IllegalArgumentException ex) {
System.out.println(ex);
}
System.out.println("Number of objects created: " + CircleWithException.getNumberOfObjects());
}
}
```
在`CircleWithException`对象在构建的时候,因为构造函数调用了`setRadius()`函数,真正异常抛出的函数是`setRadius()`函数;构造函数并没有处理该异常,因此异常被抛出到了主函数中,由主函数处理。
**注意:`IllegalArgumentException`是`RuntimeException`的子类,其实该异常是非检查异常,不进行处理也可以编译和运行,只不过在运行过程中会报错。**
### 3.5. finally 子句
某些时候我们需要有些代码无论是否异常都可以准确执行不会被异常所影响这时可以使用finally子句语法是这样的
```java
try {
statements;// 可能产生异常的语句
}
catch(TheException ex) {
handling ex; // 异常执行
}
finally {
finalStatements; // 总会执行
}
```
这个语法有个特点就是哪怕在try语法块中执行了return操作finally语法块中的语句也会在return前执行。
```java
public class Test {
public static void main(String[] args) {
try {
int b = 100;
if (b > 0)
return;
int i = Integer.parseInt("a");
System.out.print("The value is:" + i);
} catch (Exception e) {
System.out.print(e.getMessage());
} finally {
System.out.print("Finally...");
}
}
}
```
例如在try语法块中并不会引发异常处理因为在`int i = Integer.parseInt("a");`这一行前就return了。但是finally语法块中的代码任然会执行。
### 3.6. 注意事项
> Exception handling separates error-handling code from normal programming tasks, thus making programs easier to read and to modify. Be aware, however, that exception handling usually requires more time and resources because it requires instantiating a new exception object, rolling back the call stack, and propagating the errors to the calling methods.
>
> An exception occurs in a method. If you want the exception to be processed by its caller, you should create an exception object and throw it. If you can handle the exception in the method where it occurs, there is no need to throw it.
>
> When should you use the try-catch block in the code? You should use it to deal with unexpected error conditions. Do not use it to deal with simple, expected situations. For example, the following code
异常处理把代码逻辑与错误处理进行了分离使得程序更容易阅读和修改。需要注意的是异常处理通常需要更多的存储和CPU资源因为要生成和处理异常对象、对函数调用栈进行回溯、以异常信息的传递。
异常源自函数,如果需要调用方处理异常,生成一个异常对象,然后抛出;如果只是在函数内部处理异常,就没有必要抛出。
什么时候使用 try-catch 语法?你需要进行意外处理的情况,如果错误可以预计,最好不要使用异常处理。
```java
try {
System.out.println(refVar.toString());
} catch (NullPointerException ex) {
System.out.println("refVar is null");
}
```
引用变量refVar可能为空null上述的代码中的错误是可以预计的因此最好不要使用try...catch...的语法捕获异常,应该改成下面这种:
```java
if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");
```
## 4. 自定义异常
略,留给大家自己去探索。
## 5. 本章重点
本章虽然讲述了错误处理的基本原理和内容,多数为了解;只需要掌握 `try...catch...finally` 语法就可以了。因为这个语法就够将在文件处理中被大量使用。

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Loading…
Cancel
Save