This commit is contained in:
OrangeCat 2021-07-18 22:54:56 +08:00 committed by GitHub
parent 22b1ec858d
commit 3ee7e260dc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 50 additions and 19 deletions

View File

@ -1,6 +1,6 @@
# 8. 异常处理
## 什么是异常?
## 8.1 什么是异常?
异常是程序中的一些错误使得程序没有按照预期正常执行。Java提供了异常处理机制处理异常问题。
@ -20,7 +20,7 @@
## 异常的分类
## 8.2 异常的分类
异常处理的根接口是Throwable有两个子接口分别是Error和Exception。
@ -36,7 +36,7 @@ Runtime异常程序运行时产生的异常jvm会自动处理。典型的
非Runtime异常也叫检查异常即编译器要求必须进行处理的异常例如IOException、SqlException。
## 异常处理流程
## 8.3 异常处理流程
Java异常机制用到的几个关键字try、catch、finally、throw、throws。
@ -49,21 +49,43 @@ Java异常机制用到的几个关键字try、catch、finally、throw、throw
## try-catch
## 8.4 try-catch
```java
try
{
// 程序代码
}catch(ExceptionName e1)
}catch(异常类型1 异常的变量名1)
{
//Catch 块
}
```
关键词try后的括号里面的区域为监控区域java如果发生了异常则创建异常对象并将异常抛出监控区域之外catch子句则用来捕获异常
## try-catch-finally
举个例子:
```java
import java.io.*;
public class Test{
public static void main(String args[]){
try{
int a[] = new int[2];
System.out.println("访问索引下标3:" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("抛出异常 :" + e);
}
System.out.println("超出索引范围");
}
}
```
## 8.4 try-catch-finally
finally 关键字用来创建在 try 代码块后面执行的代码块。
@ -88,32 +110,41 @@ try{
## throws/throw
## 8.5 throws/throw
如果一个方法没有捕获到一个检查性异常,那么该方法必须使用 throws 关键字来声明。throws 关键字放在方法签名的尾部。
也可以使用 throw 关键字抛出一个异常,无论它是新实例化的还是刚捕获到的。
下面方法的声明抛出一个 RemoteException 异常:
throws通用格式如下:
```java
import java.io.*;
public class className {
public void deposit(double amount) throws RemoteException
{ // Method implementation throw new RemoteException(); } //Remainder of class definition }
访问权限 返回值类型 方法名称(参数列表) throws 异常类
{
// 方法体;
}
```
一个方法可以声明抛出多个异常,多个异常之间用逗号隔开。
例如,下面的方法声明抛出 RemoteException 和 InsufficientFundsException
以上方法的异常类对象都是由JVM自动实例化的如果需要手动实例化则需要用到throw关键字
```java
import java.io.*;
public class className { public void withdraw(double amount) throws RemoteException, InsufficientFundsException { // Method implementation } //Remainder of class definition }
public class Test {
public static void main(String[] args) {
try {
throw new ArrayIndexOutOfBoundsException("数组越界");
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界le!");
System.out.println("异常:" + e);
}
}
}
```
throw语句用在方法体内抛出的是一个异常实例与try-catch语句或者throws配合使用不可单独使用。
## 自定义异常
在 Java 中你可以自定义异常。编写自己的异常类时需要记住下面的几点。