异常
异常
本篇整理 Java 异常的概述与体系结构、常见异常、异常处理(try-catch-finally、throws、throw)以及自定义异常类。
1. 概述及异常体系结构
在使用计算机语言进行项目开发的过程中,即使程序员把代码写得尽善尽美,在系统运行过程中仍然会遇到一些问题,因为很多问题不是靠代码能够避免的,比如客户输入数据的格式、要读取的文件是否存在、网络是否始终保持通畅等等。
异常:程序执行中发生的不正常情况称为异常(开发过程中的语法错误和逻辑错误不是异常)。
所有的异常都有一个共同的祖先 Throwable(可抛出,这是一个类),所有的异常分成两大类(Throwable 的两个实现类):
| 分类 | 含义 | 典型示例 | 处理方式 |
|---|---|---|---|
Error | Java 虚拟机无法解决的严重问题,如 JVM 系统内部错误、资源耗尽等严重情况 | StackOverflowError、OutOfMemoryError | 一般不编写针对性的代码进行处理 |
Exception | 其它因编程错误或偶然的外在因素导致的一般性问题 | ArithmeticException、NullPointerException、ArrayIndexOutOfBoundsException、ClassCastException | 可以使用针对性的代码进行处理 |
我们接下来主要围绕 Exception 进行学习。Exception 按照编译器是否强制处置,分为两类:
| 分类 | 含义 | 处理要求 |
|---|---|---|
| 运行时异常 | java.lang.RuntimeException 类及其子类,编译器不要求强制处置的异常 | 一般由程序逻辑错误引起,程序应从逻辑角度尽可能避免这类异常的发生。这类异常很普遍,可以不作处理,若全部处理可能会对程序的可读性和运行效率产生影响 |
| 编译时异常 | 除 RuntimeException 及其子类以外,其他的 Exception 类及其子类 | 编译器要求必须处置:Java 程序必须捕获或声明所有编译时异常,如果程序不处理,可能会带来意想不到的结果 |
2. 常见异常
常见异常演示:
public class MyTest1 {
public static void main(String[] args) {
//test1();
//test2();
//test3();
//test4();
//test5();
//test6();
}
//OutOfMemoryError
public static void test1() {
int[] arr = new int[1024*1024*1024]; //int 4GB
System.out.println("************************");
}
//StackOverflowError
public static void test2() {
test2();//递归调用自身,最终抛出 StackOverflowError
}
//ArithmeticException
public static void test3() {
int a = 10/0;
}
//NullPointerException
public static void test4() {
String str = null;
System.out.println(str.length());
}
//ArrayIndexOutOfBoundsException
public static void test5() {
int[] arr = new int[5];
arr[5] = 100;
}
//ClassCastException
public static void test6() {
Object obj = new Object();
String str = (String)obj;
}
}3. 异常处理
Java 采用的异常处理机制,是将异常处理的程序代码集中在一起,与正常的程序代码分开,使得程序简洁、优雅,并易于维护。
Java 对异常处理采用抓抛模型。Java 程序的执行过程中如出现异常,会生成一个异常类对象,该异常对象将被提交给 Java 运行时系统,这个过程称为抛出异常。
异常对象的产生方式有两种:
- JVM 自动生成:程序运行过程中,虚拟机检测到程序发生了问题,如果在当前代码中没有找到相应的处理程序,就会在后台自动创建一个对应异常类的实例对象并抛出;
- 开发人员手动创建:如
Exception exception = new ClassCastException();,创建好的异常对象不抛出对程序没有任何影响,和创建一个普通对象一样。
如果一个方法中产生了异常,通常有两种处理方式:
- 在方法内部处理;
- 如果方法内部没有处理,会抛给调用者,……如果一直没有处理,最后会抛给
main方法,main方法会将异常抛给 JVM,此时程序崩溃。
3.1 try-catch-finally
基本结构:
try{
//可能产生异常的代码
} catch(ExceptionName1 e ){
//当产生ExceptionName1型异常时的处置措施
} catch(ExceptionName2 e ){
//当产生ExceptionName2型异常时的处置措施
}finally{
//无论是否发生异常,都无条件执行的语句
}try
- 捕获异常的第一步是用
try{…}语句块选定捕获异常的范围,将可能出现异常的代码放在try语句块中。
catch
- 在
catch语句块中编写对异常对象进行处理的代码。每个try语句块可以伴随一个或多个catch语句,用于处理可能产生的不同类型的异常对象; - 如果明确知道产生的是何种异常,可以用该异常类作为
catch的参数,也可以用其父类作为catch的参数; getMessage():获取异常信息,返回字符串;printStackTrace():获取异常类名和异常信息,以及异常出现在程序中的位置,返回值void。
finally
- 捕获异常的最后一步是通过
finally语句为异常处理提供一个统一的出口,使得在控制流转到程序的其它部分以前,能够对程序的状态作统一的管理; - 不论在
try代码块中是否发生了异常事件,catch语句是否执行,catch语句是否有异常,catch语句中是否有return,finally块中的语句都会被执行; finally语句是任选的。
public class MyTest2 {
public static void main(String[] args) {
int result = 0;
try {
result = 100 / 0;
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
System.out.println("-----------------------");
}
}
}
public class MyTest3 {
public static void main(String[] args) {
//创建Properties
Properties prop = new Properties();
//加载配置文件
try {
prop.load(new FileInputStream("jdbc.properties"));
//获取配置文件中key对应的value
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println(username);
System.out.println(password);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}3.2 throws
如果一个方法中的语句执行时可能生成某种异常,但是并不能确定如何处理这种异常,则此方法应显式地声明抛出异常,表明该方法将不对这些异常进行处理,而由该方法的调用者负责处理。
在方法声明中用 throws 语句可以声明抛出异常的列表,throws 后面的异常类型可以是方法中产生的异常类型,也可以是它的父类。
基本结构:
[修饰符] 返回值类型 方法名(参数列表) throws 异常类型1, 异常类型2 {
}案例:
public class MyTest4 {
public static void main(String[] args) {
try {
div(100, 0);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int div(int a, int b) throws Exception {
return a / b;
}
}
public class MyTest5 {
public static void main(String[] args) {
try {
read();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void read() throws IOException {
//创建Properties
Properties prop = new Properties();
//加载配置文件
prop.load(new FileInputStream("jdbc.properties"));
//获取配置文件中key对应的value
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println(username);
System.out.println(password);
}
}Java 异常类对象除在程序执行过程中出现异常时由系统自动生成并抛出外,也可根据需要人工创建并抛出:首先要生成异常类对象,然后通过 throw 语句实现抛出操作(提交给 Java 运行环境)。
public class MyTest6 {
public static void main(String[] args) {
try {
div(100, 0);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int div(int a, int b) throws Exception {
if(b == 0) {
throw new Exception("除数为0");
}
return a / b;
}
}4. 自定义异常类
自定义异常类继承 Exception 或它的子类。
自定义异常最重要的是异常类的名字,当异常出现时,可以根据名字判断异常类型。
public class MyException extends Exception {
//构造方法
public MyException(String msg) {
super(msg);//调用父类的构造方法
}
}
public class MyTest7 {
public static void main(String[] args) {
try {
div(100, 0);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int div(int a, int b) throws MyException {
if(b == 0) {
throw new MyException("除数为0");
}
return a / b;
}
}