异常处理
文章目录
异常概述与异常体系结构
异常:在Java语言中,将程序执行中发生的不正常情况称为“异常” 。 (开发过程中的语法错误和逻辑错误不是异常)
Java 程序在执行过程中所发生的异常事件可分为两类:
-
Error: Java 虚拟机无法解决的严重问题。如:JVM 系统内部错误、资源耗尽等严重情况。
package com.laoyang.test1; /** * ErrorTest */ public class ErrorTest { /** Error:Java 虚拟机无法解决的严重问题 > 出现这种异常情况的时候只能改代码 */ public static void main(String[] args) { // 栈溢出:java.lang.StackOverflowError // main(args); // 堆溢出:java.lang.OutOfMemoryError: Java heap space Integer[] arr = new Integer[1024 * 1024 * 1024]; } }
比如:StackOverflowError 和 OOM。一般不编写针对性 的代码进行处理。
-
Exception: 其它因编程错误或偶然的外在因素导致的一般性问题,可以使 用针对性的代码进行处理。
package com.laoyang.test1; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.lang.reflect.Field; import java.util.Date; import java.util.Scanner; /** * ExceptionTest */ public class ExceptionTest { // -----------------------------编译时异常------------------------------- /** * 文件未找到异常:FileNotFoundException * 流异常:IOException */ @Test public void testChecked() { // File file = new File("hello.txt"); // FileInputStream fileInputStream = new FileInputStream(file); // int read = fileInputStream.read(); // while (read != -1) { // System.out.println((char) read); // read = fileInputStream.read(); // } // fileInputStream.close(); } // -----------------------------运行时异常------------------------------- /** * 空指针异常:java.lang.NullPointerException */ @Test public void testOne() { int[] arr = null; System.out.println(arr[2]); String str = "abc"; str = null; System.out.println(str.charAt('a')); } /** * 数组角标越界:java.lang.ArrayIndexOutOfBoundsException */ @Test public void testTwo() { int[] arr = new int[2]; System.out.println(arr[3]); } /** * 类型转换异常:java.lang.ClassCastException */ @Test public void testThree() { Object obj = new Date(); String str = (String) obj; } /** * 数值转换异常:java.lang.NumberFormatException */ @Test public void testFour() { String str = "123"; str = "abc"; int num = Integer.parseInt(str); } /** * 输入不匹配异常:java.util.InputMismatchException */ @Test public void testFives() { Scanner scanner = new Scanner(System.in); int i = scanner.nextInt(); System.out.println(i); } /** * 算术异常:java.lang.ArithmeticException */ @Test public void testSix() { int i = 10; int j = 0; System.out.println(i / j); } }
例如:空指针访问、试图读取不存在的文件、网络连接中断 、数组角标越界(上方案例代码中的异常可以自行测试查看对应效果)。
对于这些错误,一般有两种解决方法:一是遇到错误就终止程序的运行。另一种方法是由程序员在编写程序时,就考虑到错误的检测、错误消息的提示,以及错误的处理。
捕获错误最理想的是在编译期间,但有的错误只有在运行时才会发生。 比如:除数为 0,数组下标越界等,分为编译时异常和运行时异常
异常体系结构
说明:
java.lang.Throwable
java.lang.Error:一般不编写针对性的代码进行处理(错误后缀是Error的那么就表示是一个Error错误)
java.lang.Exception:可以进行异常的处理
编译时异常(checked):比如 IOException、ClassNotFoundException、FileNotFoundException 等…
运行时异常(unchecked):比如 NullException、ArrayIndexOutOfBoundsException、ClassCastException、ArithmeticException 等…
异常处理机制
在编写程序时,经常要在可能出现错误的地方加上检测的代码, 如进行 x/y 运算时,要检测分母为 0,数据为空,输入的不是数据而是字符等。过多的 if-else 分支会导致程序的代码加长、臃肿,可读性差,因此采用异常处理机制。
Java异常处理
Java 采用的异常处理机制,是将异常处理的程序代码集中在一起,与正常的程序代码分开,使得程序简洁、优雅,并易于维护。
Java异常处理的方式
异常的处理:抓抛模型
过程一:“抛”,程序在正常执行的过程中,一旦出现异常,就会在异常代码处生成一个对应异常类的对象,并将此对象抛出。
注意:一旦抛出对象,后面的代码将不再执行
关于异常对象的产生:
- 系统自动生成的异常对象
- 手动的生成一个异常对象,并抛出
过程二:“抓”,可以理解为异常的处理方式:
- try-catch-finally
- throws
方式一:try-catch-finally
语法
try{
// 可能出现异常的代码
}catch(异常类型1 变量名1){
// 处理异常的方式1
}catch(异常类型2 变量名2){
// 处理异常的方式2
} ...
finally{
// 一定会执行的代码
}
说明
- finally 是可选的
- 使用 try 将可能出现异常的代码包装起来,在执行过程中,一旦出现异常,就会生成一个对应异常类的对象,根据此对象的类型,去 catch 中进行匹配
- 一旦 try 中的异常对象匹配到某一个 catch 时,就进入 catch 中进行异常处理,一旦处理完成,就跳出当前的 try-catch 结构(前提:在没有 finally 的情况时),然后继续执行后面的代码
- catch 中的异常类型,如果没有子父类关系,则谁声明在上,谁声明在下都没关系;如果满足父子关系,则要求子类一定声明在父类的上面,否则就会报错!
- 常用的异常对象处理的方式: ① String getMessage() ② printStackTrace()
- 在 try 结构中声明的变量,在出了 try 结构以后,就不能再被调用了
- try-catch-finally 结构是可以嵌套使用的
注意:
1. 使用 try-catch-finally 处理编译时异常,使得程序在编译时就不再报错,但是运行时仍可能报错;相当于我们使用 try-catch-finally 将一个编译时可能出现的异常,延迟到运行时出现
2. 开发中,由于运行时异常比较常见,所以通常就不针对运行时异常编写 try-catch-finally 了;针对编译时异常,一定要考虑异常的处理
案例
package com.laoyang.test1;
import org.junit.Test;
/**
* ExceptionTests 异常处理
*/
public class ExceptionTests {
@Test
public void testOne() {
String str = "123";
str = "abc";
try {
int num = Integer.parseInt(str);
System.out.println(num);
} catch (NumberFormatException e) {
// 返回一个字符串,打印报错信息
System.out.println("数值转换异常:" + e.getMessage());
// 打印堆栈报错信息,比较常用
e.printStackTrace();
} catch (Exception e) {
System.out.println(e);
}
}
}
因为 finally 结构是可选的,所以该案例中暂时没有使用 finally 结构
finally 结构的使用
- finally 是可选的
- finally 中声明的是一定会被执行的代码,即使 catch 又出现异常了,或 try 中有 return 语句,catch 中有 return 等情况
- 像数据库连接、输入输出流、网络编程中的 Socket 等资源,JVM 是不能自动回收的,需要我们自己手动进行资源的释放;此时的释放操作就需要放在 finally 中
package com.laoyang.test1;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* FinallyTest finally的使用
*/
public class FinallyTest {
/**
* 案例一
*/
@Test
public void testOne() {
int i = 10;
int j = 0;
try {
System.out.println(i / j);
} catch (ArithmeticException e) {
e.printStackTrace();
int[] arr = new int[2];
System.out.println(arr[5]);
} finally {
System.out.println("我就知道这玩意必报错!!!");
}
}
/**
* 案例二
*/
public int method() {
try {
int[] arr = new int[2];
System.out.println(arr[5]);
return 1;
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
return 2;
} finally {
System.out.println("我一定会被执行!");
return 3;
}
}
@Test
public void testTwo() {
int num = method();
// 返回 3,因为 finally 结构一定会被执行
System.out.println(num);
}
/**
* 案例三
*/
@Test
public void testThree() {
FileInputStream fileInputStream = null;
try {
File file = new File("hello.txt");
fileInputStream = new FileInputStream(file);
int read = fileInputStream.read();
while (read != -1) {
System.out.println((char) read);
read = fileInputStream.read();
}
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileInputStream != null) {
// 释放对应资源
fileInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
方式二:throws + 异常类型
说明
-
“throws + 异常类型” 写在方法的声明处,指明此方法执行时,可能会抛出的异常类型;一旦方法体执行时出现异常,仍会在异常代码处生成一个异常类的对象,此对象满足 throws 后的异常类型时,就会被抛出。
异常代码后续的代码就不会在被执行了。
-
两种异常处理方式的区别:
try-catch-finally:真正的将异常给处理掉了。
throws 的方式只是将异常抛给了方法的调用者,并没有将异常处理掉。 -
开发中如何选择使用 try-catch-finally 还是 throws?
① 如果父类中被重写的方法没有使用 throws 的方式处理异常,则子类重写的方法也不能使用 throws,也就意味着子类重写方法中有异常,那么就必须使用 try-catch-finally 的方式处理② 执行的方法中,先后又调用了另外几个方法,这几个反方是递进关系执行的;建议这几个反方使用 throws 的方式进行处理,而执行的方法 A 可以考虑使用 try-catch-finally 的方式进行处理
案例
package com.laoyang.test2;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* ExceptionTest
* 异常处理的方式二:throws + 异常类型
*/
public class ExceptionTest {
public static void main(String[] args) {
try {
testTwo();
} catch (IOException e) {
e.printStackTrace();
}
testThree();
}
@Test
public static void testOne() throws FileNotFoundException, IOException {
File file = new File("hello.txt");
FileInputStream fileInputStream = new FileInputStream(file);
int read = fileInputStream.read();
while (read != -1) {
System.out.println((char) read);
read = fileInputStream.read();
}
fileInputStream.close();
}
/**
* 因为 FileNotFoundException 是 IOException 的子类,所以在继承或者在使用的时候,我们只写一个IOException 也不会有问题
*/
@Test
public static void testTwo() throws IOException {
testOne();
}
@Test
public static void testThree() {
try {
testTwo();
} catch (IOException e) {
e.printStackTrace();
}
}
}
方法重写的规则之一
子类重写的方法抛出的异常类型不大于父类被重写的反方抛出的异常类型
package com.laoyang.test2;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* OverrideTest 方法重写的规则之一
*/
public class OverrideTest {
public static void main(String[] args) {
OverrideTest overrideTest = new OverrideTest();
overrideTest.display(new SubClass());
}
public void display(SubClass subClass) {
try {
subClass.method();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class SuperClass {
public void method() throws IOException {}
}
class SubClass extends SuperClass {
@Override
public void method() throws FileNotFoundException {}
}
自定义异常类
如何自定义异常类?
- 继承于现有的异常结构:RuntimeException(运行时异常)、Exception(编译时异常)
- 提供全局常量:serialVersionUID
- 提供重载的构造器
package com.laoyang.test3;
/**
* MyException 自定义异常类
*/
public class MyException extends RuntimeException {
static final long serialVersionUID = -7034897190745766939L;
public MyException() {
}
public MyException(String message) {
super(message);
}
}
如果一时之间忘记如何编写,那么可以进入到 任意一个异常类中查看里面的结构(比如 Exception、IOException、RuntimeException 等),然后根据对应的结构编写自己所需要的自定义异常类!
throw(手动抛出异常)的使用
package com.laoyang.test3;
/**
* StudentTest 手动抛出异常
*/
public class StudentTest {
public static void main(String[] args) {
try {
Student student = new Student();
student.regist(-1001);
System.out.println(student);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Student {
private int id;
public void regist(int id) throws Exception {
if (id > 0) {
this.id = id;
} else {
// System.out.println("您输入的数据有误!");
// throw new RuntimeException("您输入的数据有误!");
// 因为 Exception 属于编译时异常,所以如果直接new的话会直接报错,所以需要使用 try-catch-finally 或 throws 配合使用
// throw new Exception("您输入的数据有误!");
// 使用自定义异常类抛出异常
throw new MyException("您输入的数据有误");
// 错误抛出
// throw new String("您输入的数据有误");
}
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
'}';
}
}
在 Student 类的 regist() 方法中,我们在 else 中抛出了各种异常,大家可自行打开注释进行测试
相关案例
案例一
判断程序的输出结果
package com.laoyang.test4;
/**
* AbnormalPractice
*/
public class AbnormalPractice {
public static void main(String[] args) {
try {
methodA();
} catch (Exception e) {
System.out.println(e.getMessage());
}
methodB();
}
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");
}
}
}
结果为:
进入方法A
用A方法的finally
制造异常
进入方法B
调用B方法的finally
案例二
- 编写应用程序 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;
package com.laoyang.test4;
/**
* EcmDef
*/
public class EcmDef {
public static void main(String[] args) {
// 修改命令行参数查看对应效果
args = new String[]{"-5", "3"};
try {
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
int result = ecm(i, j);
System.out.println(result);
} catch (NumberFormatException e) {
System.out.println("参数类型不一致!");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("缺少命令行参数!");
} catch (ArithmeticException e) {
System.out.println("除数不能为0!");
} catch (EcDef e) {
System.out.println(e.getMessage());
}
}
public static int ecm(int i, int j) throws EcDef {
if (i < 0 || j < 0) {
throw new EcDef("参数不能为负数");
}
return i / j;
}
}
/**
* 自定义异常类
*/
class EcDef extends Exception {
static final long serialVersionUID = -3387516993124229948L;
public EcDef() {
}
public EcDef(String message) {
super(message);
}
}
为了方便,我这里的自定义异常类就直接写在同一个类中了,大家在实际开发中一定要拆分编写,否则不利于维护与后期编写
常见面试题
一、常见的异常有哪些?
运行时异常:RuntimeException、ClassCastException 、NullPointerException
编译时异常:ClassCastException 、IOException、SQLException
二、final、finally 与 finalize 的区别?
final :
-
修饰符(关键字) 如果一个类被声明为final,意味着它不能再派生新的子类,不能作为父类被继承。因此一个类不能及被声明为 abstract,又被声明为 final 的。
-
将变量或方法声明为 final,可以保证他们使用中不被改变。被声明为 final 的变量必须在声明时给定初值,而以后的引用中只能读取,不可修改,被声明为 final 的方法也同样只能使用,不能重载。
finally:
- 在异常处理时提供finally块来执行清楚操作。如果抛出一个异常,那么相匹配的catch语句就会执行,然后控制就会进入finally块,如果有的话。
finalize:
-
是方法名。java技术允许使用finalize()方法在垃圾收集器将对象从内存中清除之前做必要的清理工作。这个方法是在垃圾收集器在确定了,被清理对象没有被引用的情况下调用的。
-
finalize是在Object类中定义的,因此,所有的类都继承了它。子类可以覆盖finalize()方法,来整理系统资源或者执行其他清理工作。