前言
本篇笔记将对 Java
基础部分内容的 “异常处理” 章节知识点进行梳理、复盘、总结。
“温故而知新”
目录
异常处理
0x01:异常概述
在 Java
语言中, 将程序执行中发生的不正常情况称为“异常” (开发过程中的语法错误和逻辑错误不是异常) ,Java
程序在执行过程中所发生的异常事件可分为两类:
-
Error:
Java
虚拟机无法解决的严重问题。 如:JVM
系统内部错误、 资源耗尽等严重情况。 比如:StackOverflowError
和OOM
。 一般不编写针对性的代码进行处理。 -
Exception: 其它因编程错误或偶然的外在因素导致的一般性问题, 可以使用针对性的代码进行处理。 例如:空指针访问
- 试图读取不存在的文件
- 网络连接中断
- 数组角标越界
对于这些错误, 一般有两种解决方法:
- 一是遇到错误就终止程序的运行。
- 另一种方法是由程序员在编写程序时, 就考虑到错误的检测、 错误消息的提示, 以及错误的处理。
捕获错误最理想的是在编译期间, 但有的错误只有在运行时才会发生。比如: 除数为 0
, 数组下标越界等
分类: 编译时异常和运行时异常
-
运行时异常
-
是指编译器不要求强制处置的异常。一般是指编程时的逻辑错误,是程序员应该积极避免其出现的异常。
java.lang.RuntimeException
类及它的子类都是运行时异常。 -
对于这类异常,可以不作处理,因为这类异常很普遍,若全处理可能会对程序的可读性和运行效率产生影响。
-
-
编译时异常
- 是指编译器要求必须处置的异常。即程序在运行时由于外界因素造成的一般性异常。 编译器要求
Java
程序必须捕获或声明所有编译时异常。 - 对于这类异常,如果程序不处理,可能会带来意想不到的结果。
- 是指编译器要求必须处置的异常。即程序在运行时由于外界因素造成的一般性异常。 编译器要求
0x02:常见的异常
java.lang.Error
:一般不编写针对性的代码进行处理java.lang.Exception
: 可以进行异常的处理,所有的异常类型都继承与该类。而Exception
又继承于java.lang.Throwable
运行时异常
-
IOException
- FileNotFoundException(文件未找到)
-
ClassNotFoundException
编译时的异常
在此只列出较为常见的
- 空指针异常:NullPointerException
@Test
public void test1(){
String str = "abc";
str = null;
System.out.println(str.charAt(0));
}
- 越界异常:IndexOutOfBoundsException
@Test
public void test2(){
//数组角标越界:ArrayIndexOutOfBoundsException
int[] arr = new int[10];
System.out.println(arr[10]);
//字符串角标越界:StringIndexOutOfBoundsException
String str = "abc";
System.out.println(str.charAt(3));
}
- 类型转换异常:ClassCastException
@Test
public void test3(){
Object obj = new Date();
String str = (String)obj;
- 数值转换异常:NumberFormatException
@Test
public void test4(){
String str = "123";
str = "abc";
int num = Integer.parseInt(str);
}
- 输入异常:InputMismatchException
@Test
public void test5(){
Scanner scanner = new Scanner(System.in);
int score = scanner.nextInt();
System.out.println(score);
scanner.close();
}
- 算数异常:ArithmeticException
@Test
public void test6(){
int a = 10;
int b = 0;
System.out.println(a / b);
}
0x03:异常的处理:抓抛模型
异常的处理方式一:“抓”
可以理解为异常的处理方式,将异常可能出现的代码进行捕获、处理
常见的处理方式有
try-catch-finally
throws
try-catch-finally 的基本使用:
try{
//可能出现异常的代码
}catch(异常类型1 变量名1){
//处理异常的方式1
}catch(异常类型2 变量名2){
//处理异常的方式2
}catch(异常类型3 变量名3){
//处理异常的方式3
}
finally{
//一定会执行的代码
}
运行时异常的例子:
@Test
public void test1(){
String str = "123";
str = "abc";
int num = 0;
try{
num = Integer.parseInt(str);
System.out.println("hello-----1");
}catch(NumberFormatException e){
System.out.println("出现数值转换异常了,不要着急....");
//String getMessage():
System.out.println(e.getMessage());
//printStackTrace():
e.printStackTrace();
}catch(NullPointerException e){
System.out.println("出现空指针异常了,不要着急....");
}catch(Exception e){
System.out.println("出现异常了,不要着急....");
}
System.out.println(num);
System.out.println("hello-----2");
}
编译时异常的例子:
@Test
public void test2(){
try{
File file = new File("hello.txt");
FileInputStream fis = new FileInputStream(file);
int data = fis.read();
while(data != -1){
System.out.print((char)data);
data = fis.read();
}
fis.close();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
finally 的使用:
@Test
public void test2(){
FileInputStream fis = null;
try {
File file = new File("hello1.txt");
fis = new FileInputStream(file);
int data = fis.read();
while(data != -1){
System.out.print((char)data);
data = fis.read();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fis != null) //文件不存在时得到对象的值为null
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
对上述内容进行总结
- 使用
try-catch-finally
处理编译时异常,使得程序在编译时就不再报错,但是运行时仍可能报错。相当于我们使用try-catch-finally
将一个编译时可能出现的异常,延迟到运行时出现。 - 开发中,由于运行时异常比较常见,所以我们通常就不针对运行时异常编写
try-catch-finally
了。针对于编译时异常,我们说一定要考虑异常的处理。
使用总结:
-
finally
是可选的 -
使用
try
将可能异常的代码包装起来,一旦出现异常,就会生成一个对应异常类的对象,根据此对象的类型,去catch
中进行匹配 -
一旦
try
中的异常对象匹配到某一个catch
时,就会进入到catch
的代码块中进行异常处理,一旦处理完成,就跳出当前的try-catch
结构(在没有写finally
的情况)。继续执行其后的代码 -
常用的异常对象处理的方式:
String getMessage()
printStackTrace()
-
在
try
结构中声明的变量,再出了try
结构以后,就不能再被调用 -
try-catch-finally
结构可以嵌套
异常的处理方式二:“抛”
关键字:throws
程序在正常执行的过程中,一旦出现异常,就会在异常代码处生成一个对应的异常类对象,并将此对象抛出。一旦抛出该对象以后,其后的代码就不再执行。
-
"
throws
+ 异常类型" 写在方法的声明处,当指明此方法执行时,可能会抛出的异常类型。 -
一旦当方法体执行时,出现异常,仍会在异常代码处生成一个异常类的对象,此对象满足
throws
后异常类型时,就会被抛出。异常代码后续的代码,就不再执行!
如下例子
public static void main(String[] args){
try{
method2();
}catch(IOException e){
e.printStackTrace();
}
// method3();
}
public static void method3(){
try {
method2();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void method2() throws IOException{
method1();
}
public static void method1() throws FileNotFoundException,IOException{
File file = new File("hello1.txt");
FileInputStream fis = new FileInputStream(file);
int data = fis.read();
while(data != -1){
System.out.print((char)data);
data = fis.read();
}
fis.close();
System.out.println("hahaha!");
}
重写的规则:
“ 子类重写的方法抛出的异常类型,不能大于父类被重写的方法所抛出的异常类型 ”
public class OverrideTest {
public static void main(String[] args) {
OverrideTest test = new OverrideTest();
test.display(new SubClass());
}
public void display(SuperClass s){
try {
s.method();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class SuperClass{
public void method() throws IOException{
}
}
class SubClass extends SuperClass{
// public void method()throws Exception {
//
// }
public void method()throws FileNotFoundException{
}
}
从上面的例子中,如果 SubClass
抛出的是 Exception
异常,而父类的被重写的方法所抛出为 IOException
,此时编译则无法通过,因为 Exception
异常包含了所有的异常类型,而父类只能接受子类抛出的 IOException
一些体会
-
try-catch-finally
: 真正的将异常给处理掉了,而throws
的方式只是将异常抛给了方法的调用者。并没有真正将异常处理掉。 -
在实际开发中如何选择使用
try-catch-finally
还是使用throws
?- 如果父类中被重写的方法没有
throws
方式处理异常,则子类重写的方法也不能使用throws
,这意味着,如果子类重写的方法中有异常,必须使用try-catch-finally
方式处理。 - 执行的方法
a
中,先后又调用了另外的几个方法,这几个方法是递进关系执行的。我们建议这几个方法使用throws
的方式进行处理。而执行的方法a
可以考虑使用try-catch-finally
方式进行处理。
- 如果父类中被重写的方法没有
0x04:手动抛出异常对象
关键字:throw
,体现的是生成一个异常对象,在方法体内定义
区别于
throws
,体现的是异常的处理,在方法的声明处处定义
如下例子
public class StudentTest {
public static void main(String[] args) {
try {
Student s = new Student();
s.regist(-1001);
System.out.println(s);
} catch (Exception e) {
// e.printStackTrace();
//获取异常中的提示信息
System.out.println(e.getMessage());
}
}
}
class Student{
private int id;
public void regist(int id) throws Exception {
if(id > 0){
this.id = id;
}else{
// System.out.println("您输入的数据非法!");
//手动抛出异常对象
// throw new Exception("您输入的数据非法!");
throw new RuntimeException("您输入的数据非法!");
}
}
@Override
public String toString() {
return "Student [id=" + id + "]";
}
}
0x05:自定义异常类
如何自定义异常类?
-
① 继承于现有的异常结构:
RuntimeException
、Exception
-
② 提供全局常量:
serialVersionUID
(用于IO传输时校验两个对象是否相等) -
③ 提供重载的构造器
构建一个自定义异常类 MyException
,继承于 MyException
,如下代码
public class MyException extends Exception{
static final long serialVersionUID = -7034897193246939L;
public MyException(){
}
public MyException(String msg){
super(msg);
}
}
修改 0x04
章节例子中的代码,抛出我们自定义的异常类
public void regist(int id) throws Exception {
if(id > 0){
this.id = id;
}else{
//throw new RuntimeException("您输入的数据非法!");
throw new MyException("不能输入负数");
}
}
运行结果:
不能输入负数
RuntimeException
和 Exception
的区别是什么?
-
Exception:受检查异常。可以理解为错误,必须要开发者解决以后才能编译通过,解决的方法有以下两种:
throw
到上层try-catch
处理
-
RunTimeException:运行时异常,又称不受检查异常,不受检查!
因为不受检查,所以在代码中可能会有
RunTimeException
时Java
编译检查时不会告诉你有这个异常,但是在实际运行代码时则会暴露出来,比如经典的1/0
,空指针等。如果不处理也会被Java
自己处理。
0x06:一些问题
throw
与 throws
的区别是什么?
throw
可以主动的在代码中抛出异常,也可以使用该关键字抛出自定义的异常类throws
用于声明异常,将方法中出现的异常向上(调用方)抛出,由调用方去决定如何处理该异常。
上游排污(throw)下游(throws)治污
总结
总结:异常处理的 5
个关键字
try
、catch
、finally
、throw
、throws
“一首小悟”
- 世界上最遥远的 距离,是我在
if
里你在else
里,似乎一直相伴又永远分离; - 世界上最痴心的 等待,是我当
case
你是switch
,或许永远都选不上自己; - 世界上最真情的 相依,是你在
try
我在catch
。无论你发神马脾气,我都默默承受,静静处理。到那时,再来期待我们的finally
。