本文已参与「新人创作礼」活动,一起开启掘金创作之路。
异常是程序中的一些错误,但并不是所有的错误都是异常,并且错误有时候是可以避免的。
一、基本概念
程序执行过程中发生的不正常行为称为异常。比如说,你的代码少了一个分号,那么运行出来结果是提示是错误 java.lang.Error;如果你用System.out.println(11/0),那么你是因为你用0做了除数,会抛出 java.lang.ArithmeticException 的异常。
异常发生的原因有很多,通常包含以下几大类:
- 用户输入了非法数据。
- 要打开的文件不存在。
- 网络通信时连接中断,或者JVM内存溢出。
这些异常有的是因为用户错误引起,有的是程序错误引起的,还有其它一些是因为物理错误引起的。 要理解Java异常处理是如何工作的,你需要掌握以下三种类型的异常:
- 检查性异常: 最具代表的检查性异常是用户错误或问题引起的异常,这是程序员无法预见的。例如要打开一个不存在文件时,一个异常就发生了,这些异常在编译时不能被简单地忽略。
- 运行时异常: 运行时异常是可能被程序员避免的异常。与检查性异常相反,运行时异常可以在编译时被忽略。
- 错误: 错误不是异常,而是脱离程序员控制的问题。错误在代码中通常被忽略。例如,当栈溢出时,一个错误就发生了,它们在编译也检查不到的。
二、Exception类
所有的异常类是从 java.lang.Exception 类继承的子类。
- Exception 类是 Throwable 类的子类。除了Exception类外,Throwable还有一个子类Error 。
- Java 程序通常不捕获错误。错误一般发生在严重故障时,它们在Java程序处理的范畴之外。
- Error 用来指示运行时环境发生的错误。
异常类有两个主要的子类:IOException 类和 RuntimeException 类。(下图来源网络)
从上图中可以看到:
- Throwable: 是异常体系的顶层类,其派生出两个重要的子类, Error 和 Exception。
- Error: 指的是Java虚拟机无法解决的严重问题,比如:JVM的内部错误、资源耗尽等,典型代表:StackOverflowError和OutOfMemoryError,一旦发生回力乏术,就像人得了癌症。
- Exception: 异常产生后程序员可以通过代码进行处理,使程序继续执行。比如:感冒、发烧。我们平时所说的异常就是Exception。
三、异常的分类
异常可能在编译时发生,也可能在程序运行时发生,根据发生的时机不同,可以将异常分为:
1、检查性异常(编译时异常)
public class Person {
private String name;
private String gender;
int age;
// 想要让该类支持深拷贝,覆写Object类的clone方法即可
@Override
public Person clone() {
return (Person)super.clone();
}
}
在编译器中代码就会有红色波浪线提示代码有问题。
2、运行时异常
在程序执行期间发生的异常,称为运行时异常,也称为非受检查异常(Unchecked Exception)。 RunTimeException以及其子类对应的异常,都称为运行时异常。比如:NullPointerException、ArrayIndexOutOfBoundsException、ArithmeticException。
注: 编写代码时的语法错误不算异常。
四、异常的处理
1、防御式编程
防御式编程(Defensive Programming)是提高软件质量技术的有益辅助手段。 核心思想是: 子程序应该不因传入错误数据而被破坏,哪怕是由其他子程序产生的错误数据。
1.1 LBYL(Look Before You Leap)事先防御型
在操作前做充足的检查。
boolean ret = false;
ret = 登陆游戏();
if (!ret) {
处理登陆游戏错误;
return;
}
ret = 开始匹配();
if (!ret) {
处理匹配错误;
return;
}
ret = 游戏确认();
if (!ret) {
处理游戏确认错误;
return;
}
ret = 选择英雄();
if (!ret) {
处理选择英雄错误;
return;
}
ret = 载入游戏画面();
if (!ret) {
处理载入游戏错误;
return;
}
缺点: 正常流程和错误处理流程代码混在一起, 显的比较杂乱。
1.2 EAFP(It's Easier to Ask Forgiveness than Permission)事后认错型
遇到问题再处理。
try {
登陆游戏();
开始匹配();
游戏确认();
选择英雄();
载入游戏画面();
...
} catch (登陆游戏异常) {
处理登陆游戏异常;
} catch (开始匹配异常) {
处理开始匹配异常;
} catch (游戏确认异常) {
处理游戏确认异常;
} catch (选择英雄异常) {
处理选择英雄异常;
} catch (载入游戏画面异常) {
处理载入游戏画面异常; }
......
优点: 正常流程和错误流程是分离的, 代码更清晰,更容易理解。
注: 异常处理的核心思想就是事后认错(EAFP)。
2、异常的抛出(throw关键字)
在Java中,可以借助throw关键字,抛出一个指定的异常对象,将错误信息告知给调用者。
示例(下面方法的声明抛出一个 RemoteException 异常):
import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
//方法的实现
throw new RemoteException(); //抛出异常
}
//类的其他内容
}
一个方法声明能够抛出多个异常,多个异常使用逗号隔开。
import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
// 方法的实现
}
//类的其他内容
}
示例: 实现一个获取数组中任意位置元素的方法。
public class Test1 {
public static int getElement(int[] array, int index){
if(null == array){
throw new NullPointerException("传递的数组为null");
}
if(index < 0 || index >= array.length){
throw new ArrayIndexOutOfBoundsException("传递的数组下标越界");
}
return array[index];
}
public static void main(String[] args) {
int[] array = {1,2,3};
getElement(array, 3);
}
}
注:
- 如果抛出的是 RunTimeException 或者 RunTimeException 的子类,则可以不用处理,直接交给JVM来处理。
- 如果抛出的是编译时异常,用户必须处理,否则无法通过编译。
- 异常一旦抛出,其后的代码就不会执行。
3、 异常的捕获(throws和try-catch关键字)
3.1 异常的声明(throws)
当方法中抛出编译时异常,用户不想处理该异常,此时使用throws将异常抛给方法调用者来处理。
public class Config {
File file;
/*
FileNotFoundException : 编译时异常,表明文件不存在
此处不处理,也没有能力处理,应该将错误信息报告给调用者,让调用者检查文件名字是否给错误了
*/
public void OpenConfig(String filename) throws FileNotFoundException{
if(filename.equals("config.ini")){
throw new FileNotFoundException("配置文件名字不对");
}
// 打开文件
}
public void readConfig(){
}
}
注:
-
throws必须跟在方法的参数列表之后。
-
声明的异常必须是 Exception 或者 Exception 的子类。
-
调用声明抛出异常的方法时,调用者必须对该异常进行处理,或者继续使用throws抛出。
public static void main(String[] args) throws IOException { Config config = new Config(); config.openConfig("config.ini"); }
3.2 try-catch捕获并处理
throws对异常并没有真正处理,而是将异常报告给抛出异常方法的调用者,由调用者处理。如果真正要对异常进行处理,就需要try-catch。 使用 try 和 catch 关键字可以捕获异常。try/catch 代码块放在异常可能发生的地方。 try/catch代码块中的代码称为保护代码,使用 try/catch 的语法如下:
try
{
// 程序代码
}catch(ExceptionName e1)
{
//Catch 块
}
可以多重捕获,和if-else的逻辑相似。
try{
// 程序代码
}catch(异常类型1 异常的变量名1){
// 程序代码
}catch(异常类型2 异常的变量名2){
// 程序代码
}catch(异常类型3 异常的变量名3){
// 程序代码
}
示例: 读取配置文件,如果配置文件名字不是指定名字,抛出异常,调用者进行异常处理
public class Config {
File file;
public void openConfig(String filename) throws FileNotFoundException {
if(!filename.equals("config.ini")){
throw new FileNotFoundException("配置文件名字不对");
}
// 打开文件
}
public void readConfig(){
}
public static void main(String[] args) {
Config config = new Config();
try {
config.openConfig("config.txt");
System.out.println("文件打开成功");
} catch (IOException e) {
// 异常的处理方式
//System.out.println(e.getMessage()); // 只打印异常信息
//System.out.println(e); // 打印异常类型:异常信息
e.printStackTrace(); // 打印信息最全面
}
// 一旦异常被捕获处理了,此处的代码会执行
System.out.println("异常如果被处理了,这里的代码也可以执行");
}
}
注:
-
try块内抛出异常位置之后的代码不会被执行。
-
如果抛出异常类型与catch时异常类型不匹配,即异常不会被成功捕获,也就不会被处理,继续往外抛,直到 JVM收到后中断程序----异常是按照类型来捕获的
public static void main(String[] args) { try { int[] array = {1,2,3}; System.out.println(array[3]); // 此处会抛出数组越界异常 }catch (NullPointerException e){ // 捕获时候捕获的是空指针异常--真正的异常无法被捕获到 e.printStackTrace(); } System.out.println("后序代码"); } -
如果多个异常处理方式相同,也可以写成这样:
catch (ArrayIndexOutOfBoundsException | NullPointerException e) { ... } -
如果异常之间具有父子关系,一定是子类异常在前catch,父类异常在后catch,否则语法错误:
public static void main(String[] args) { int[] arr = {1, 2, 3}; try { System.out.println("before"); arr = null; System.out.println(arr[100]); System.out.println("after"); } catch (Exception e) { // Exception可以捕获到所有异常 e.printStackTrace(); }catch (NullPointerException e){ // 永远都捕获执行到 e.printStackTrace(); } System.out.println("after try catch"); } -
一个catch捕获所有异常(不推荐),因为Exception是所有异常类的父类,所以能够捕获所有异常。
public static void main(String[] args) { 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"); }
4、finally关键字
- finally 关键字用来创建在 try 代码块后面执行的代码块。
- 无论是否发生异常,finally 代码块中的代码总会被执行。
- 在 finally 代码块中,可以运行清理类型等收尾善后性质的语句。
try{
// 程序代码
}catch(异常类型1 异常的变量名1){
// 程序代码
}catch(异常类型2 异常的变量名2){
// 程序代码
}finally{
// 程序代码
}
示例:
public static void main(String[] args) {
try{
int[] arr = {1,2,3};
arr[100] = 10;
arr[0] = 10;
}catch (ArrayIndexOutOfBoundsException e){
System.out.println(e);
}finally {
System.out.println("finally中的代码一定会执行");
}
System.out.println("如果没有抛出异常,或者异常被处理了,try-catch后的代码也会执行");
}
==
==【提问】== finally 和 try-catch-finally 后的代码都会执行,那为什么还要有finally呢?
示例: 实现getData方法,内部输入一个整形数字,然后将该数字返回,并再main方法中打印。
public static int getData(){
Scanner sc = null;
try{
System.out.print("请输入一个数字:");
sc = new Scanner(System.in);
int data = sc.nextInt();
return data;
}catch (InputMismatchException e){
e.printStackTrace();
}finally {
System.out.println("finally中代码");
}
System.out.println("try-catch-finally之后代码"); //正常输入不执行该语句
if(null != sc){
sc.close();
}
return 0;
}
public static void main(String[] args) {
int data = getData();
System.out.println(data);
}
在正常输入数字后得到的结果:
5、异常的处理流程
- 程序先执行 try 中的代码。
- 如果 try 中的代码出现异常, 就会结束 try 中的代码, 看和 catch 中的异常类型是否匹配。
- 如果找到匹配的异常类型, 就会执行 catch 中的代码。
- 如果没有找到匹配的异常类型, 就会将异常向上传递到上层调用者。
- 无论是否找到匹配的异常类型, finally 中的代码都会被执行到(在该方法结束之前执行)。
- 如果上层调用者也没有处理的了异常, 就继续向上传递。
- 一直到 main 方法也没有合适的代码处理异常, 就会交给 JVM 来进行处理, 此时程序就会异常终止。
五、自定义异常类
虽然Java中已经给出了丰富的异常类,你仍然可以按照自己的需求编写自己的异常类。需要注意的是:
- 所有异常都必须是 Throwable 的子类。
- 如果希望写一个检查性异常类,则需要继承 Exception 类。
- 如果希望写一个运行时异常类,那么需要继承 RuntimeException 类。
可以按照以下语法格式来定义自己的异常类:
//只继承Exception 类来创建的异常类是检查性异常类。
class MyException extends Exception{
}
一个异常类和其他类一样,包含有变量和方法。 示例:
// 文件名InsufficientFundsException.java
import java.io.*;
//自定义异常类,继承Exception类
public class InsufficientFundsException extends Exception
{
//此处的amount用来储存当出现异常(取出钱多于余额时)所缺乏的钱
private double amount;
public InsufficientFundsException(double amount)
{
this.amount = amount;
}
public double getAmount()
{
return amount;
}
}
为了展示如何使用该自定义的异常类,在下面的 CheckingAccount 类中包含一个 withdraw() 方法抛出一个 InsufficientFundsException 异常。
// 文件名称 CheckingAccount.java
import java.io.*;
//此类模拟银行账户
public class CheckingAccount
{
//balance为余额,number为卡号
private double balance;
private int number;
public CheckingAccount(int number)
{
this.number = number;
}
//方法:存钱
public void deposit(double amount)
{
balance += amount;
}
//方法:取钱
public void withdraw(double amount) throws
InsufficientFundsException
{
if(amount <= balance)
{
balance -= amount;
}
else
{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
//方法:返回余额
public double getBalance()
{
return balance;
}
//方法:返回卡号
public int getNumber()
{
return number;
}
}
//文件名称 BankDemo.java
public class BankDemo
{
public static void main(String [] args)
{
CheckingAccount c = new CheckingAccount(101);
System.out.println("正在存入500元...");
c.deposit(500.00);
try
{
System.out.println("\n正在取出100元...");
c.withdraw(100.00);
System.out.println("\n正在取出600元...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{
System.out.println("抱歉,您的账户余额不足");
e.printStackTrace();
}
}
}