Java基础(九)-- 异常处理
异常概述与异常体系结构
异常:在Java中,将程序发生的不正常情况称为异常(开发过程中的语法错误和逻辑错误不是异常)
Java程序在执行过程中发生的异常事件可以分为两类:
-
Error:Java虚拟机无法解决的严重问题,如:JVM系统内部错误,资源耗尽等严重情况;一般不编写针对性的代码进行处理
如:栈溢出:java.lang.StackOverflowError、堆溢出:java.lang.OutOfMemoryError(OOM)
public class ErrorTest { public static void main(String[] args) { // 1. 栈溢出:java.lang.StackOverflowError // main(args); // 2. 堆溢出:java.lang.OutOfMemoryError(OOM) // Integer[] arr = new Integer[1024 * 1024 * 1024]; } }
-
Exception:其他因编程错误或偶然的外在因素导致的一般性问题,可以使用针对性的代码进行处理,例如:
- 空指针访问
- 试图读取不存在的文件
- 网络连接中断
- 数组角标越界
对于这种错误,一般有两种解决方法:
- 遇到错误就终止程序的运行
- 由程序员在编写程序时就考虑好错误的检测、错误消息的提示以及错误的处理
捕获错误的最理想的在编译期间,但有的错误只有在运行时才会发生,如:除数为0、数组下标越界等,根据上述情况可以将异常分为两类:
- 编译时异常
- 运行时异常
异常的体系结构
java.lang.Throwable
- java.lang.Error:一般不编写针对性的代码进行处理
- java.lang.Exceprion:可以进行异常处理
- 编译时异常(checked)
- IOException
- FileNotFoundException
- ClassNotFoundException
- IOException
- 运行时异常(unchecked)
- NullPointerException
- ArrayIndexOutOfBoundsException
- ClassCastException
- NumberFormatException
- InputMismatchException
- ArithmeticException
- 编译时异常(checked)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-syZai2B7-1623844142268)(C:\Users\911\AppData\Roaming\Typora\typora-user-images\image-20210311192018700.png)]
异常处理
在编写程序时,经常要在可能出现错误的地方加上检测的代码,但是过多的 if-else 分支会导致程序的代码加长、臃肿、可读性差,因此采用异常处理机制
Java采用的异常处理机制,是将异常处理的程序代码集中在一起,与正常的程序代码分开,是得程序简洁、优雅,并易于维护
Java提供的是异常处理的**抓抛模型**:
过程一 “抛”:程序在正常执行的过程中,一旦出现异常,就会在异常代码出生成对应异常类的对象,并将此对象抛出,一旦抛出对象后,其后的代码就不再执行
关于异常对象的产生:
- 系统自动生成的异常对象
- 手动生成一个异常对象,并抛出
throw
过程二 “抓”:这里可以理解为异常的处理方式,有两种 ① try-catch-finally ② throws
try-catch-finally
// try-catch-finally 的结构
try{
// 可能出现异常的代码
}
catch(异常类型1 变量名1){
// 处理该异常的方式
}
catch(异常类型2 变量名2){
// 处理该异常的方式
}
catch(异常类型3 变量名3){
// 处理该异常的方式
}
...
finally{
// 一定会执行的代码
}
注意:
-
finally
是可选的 -
使用
try
将可能出现异常的代码包装起来,在执行过程中,一旦出现异常,就会生成一个对应的异常对象,根据此对象的类型到catch
中进行匹配 -
一旦
try
中的异常对象匹配到某个catch
时,就进入到该catch
进行异常处理,一旦处理完成就跳出当前的try-catch
结构(但 finally 中的代码仍会执行),然后继续执行try-catch
之后的代码 -
若
catch
中的异常类型若没有子父类关系,则其声明顺序没有要求若
catch
中的异常类型若满足于子父类关系,则要求子类一定要声明在父类之前,否则报错 -
常用的异常对象处理方式:
String getMessage()
void printStackTrace()
-
在
try
中声明的变量,在 try 结构外不能调用 -
try-catch-finally
结构可以相互嵌套
注:使用 try-catch-finally
处理编译时异常,使得程序在编译时不报错,但是在运行时仍可能报错,这就相当于我们使用 try-catch-finally
将一个编译时可能出现的异常延时到运行时出现
注:开发中,由于运行时异常较为常见,所以我们通常不针对运行时异常编写 try-catch-finally
进行处理,而针对编译时异常,是一定要处理的
finally的使用
finally 使用要点:
- finally 是可选的
- finally 中的代码是一定会执行的,即便 catch 中出现异常,try-catch 结构中有
return
语句等情况下,依旧会执行(先执行finally
中代码再执行 return) - 如数据库连接、输入输出流、网络编程Socket 等资源,JVM是不能自动回收的,需要我们手动进行资源释放,此时的资源释放就需要声明在 finally 中
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.junit.Test;
public class HandleExceptionTest {
@Test
public void testFinally(){
//
File file = null;
FileInputStream fis = null;
try{
file = new File("Exception.txt");
// Unhandled exception type FileNotFoundException
fis = new FileInputStream(file);
// Unhandled exception type IOException
int data = fis.read();
while(data != -1){
System.out.println((char)data);
data = fis.read();
}
}
catch(Exception e){
e.printStackTrace();
}
finally {
try{
// 会出现异常,要进行处理
if(fis != null)
fis.close();
}
catch(IOException e){
e.printStackTrace();
}
}
}
@Test
public void testMethod(){
System.out.println(method());
}
public int method(){
try{
System.out.println("执行try中代码");
// 抛出异常
System.out.println(Integer.parseInt(null));
return 1;
}
catch(Exception e){
System.out.println("出现异常,在catch中对异常进行处理");
return 2;
}
finally {
System.out.println("finally中一定会执行的代码");
}
}
@Test
public void test(){
//
String str = "123";
str = "abc";
try{
System.out.println(Integer.parseInt(str));
System.out.println("继续执行try中代码");
}
catch(NumberFormatException e){
System.out.println("数值转换异常,处理该异常");
}
catch(NullPointerException e){
System.out.println("空指针异常,处理该异常");
}
catch(Exception e){
System.out.println("出现异常,处理该异常");
e.printStackTrace();
}
System.out.println("继续执行try-catch结构外的代码");
}
}
throws
throws + 异常类型使用结构:
method() throws Exception1, Exception2...{}
throws + 异常类型
写在方法声明处,知名此方法执行时,可能会抛出这些类型的异常,当方法执行时出现异常,仍会生成一个异常类的对象,此对象满足 throws 后的异常类型时,就会被抛出,出现异常后,其后续的代码就不再执行
注:
- try-catch-finally :真正将异常处理掉了
- throws :只是将异常抛给了方法的调用者,并没有真正将异常处理掉,调用此方法的方法仍要对抛出的异常进行处理
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class ThrowsTest {
public static void main(String[] args) {
// 最终要进行异常处理
try {
methodTest();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void methodTest() throws IOException{
// 此处调用method()时,仍要对其抛出的异常进行处理
method();
}
public static void method() throws IOException{
File file = new File("Exception.txt");
// Unhandled exception type FileNotFoundException
FileInputStream fis = new FileInputStream(file);
// Unhandled exception type IOException
int data = fis.read();
while(data != -1){
System.out.println((char)data);
data = fis.read();
}
fis.close();
}
}
重写方法抛出异常的规则
- 子类重写的方法抛出的异常类型不大于父类别重写方法抛出的异常类型,若父类未抛异常,子类也不许抛异常
import java.io.FileNotFoundException;
import java.io.IOException;
public class ExtendsThrowsTest {
public static void main(String[] args) {
try {
new SubClass().method();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class SuperClass{
public void method() throws IOException{
//
throw new IOException();
}
}
class SubClass extends SuperClass{
@Override
public void method() throws FileNotFoundException{
//
throw new FileNotFoundException();
}
}
开发中如何选择处理异常的方式
- 若父类中被重写的方法没有
throws
抛异常,则子类重写的方法也不能使用throws
来处理异常,因此必须使用try-catch-finally
的方式处理 - 执行的方法中,先后又调用了另外的几个方法,这几个方法是递进关系执行的,因此这些递进的方法建议使用 throws 的方式进行处理;而执行这些递进方法的方法,可以考虑使用
try-catch-finally
的方式进行处理
手动抛出异常(throw)
public class ThrowTest {
public static void main(String[] args) {
//
Compare2 com = new Compare2(3);
System.out.println(com.compareTo(new Object()));
}
}
class Compare2{
private int value;
public Compare2(int i){
value = i;
}
public int compareTo(Object o){
if(this == o)
return 0;
if(o instanceof Compare2){
Compare2 com = (Compare2)o;
if(this.value == com.value)
return 0;
if(this.value > com.value)
return 1;
return -1;
}
// 手动抛异常
throw new RuntimeException("传入数据格式不匹配");
}
}
自定义异常
自定义异常类:
- 继承现有的异常结构:RuntimeException、Exception
- 提供全局常量序列号:serialVersionUID
import java.util.Scanner;
public class MyExceptionTest {
public static void method(){
Scanner sc = new Scanner(System.in);
int num = 0;
// 结构中可以没有catch
try{
num = sc.nextInt();
if(num < 0)
throw new InputException("请输入正数");
}
finally{
sc.close();
}
}
public static void main(String[] args) {
try {
method();
} catch (InputException e) {
System.out.println(e.getMessage());;
}
}
}
class InputException extends RuntimeException{
/**
* @Fields 序列号
*/
private static final long serialVersionUID = 1L;
public InputException(){}
public InputException(String msg){
super(msg);
}
}
面试题
常见的异常有哪些?举例
import java.io.File;
import java.io.FileInputStream;
import java.util.Scanner;
import org.junit.Test;
public class NormalExceptionTest {
// ---------------------------运行时异常---------------------------
// NullPointerException
@Test
public void testNullPointerException(){
// 空指针异常
/*
* int[] arr = null;
* System.out.println(arr[0]);
* */
String str = null;
System.out.println(str.charAt(0));
}
// IndexOutOfBoundsException
@Test
public void testIndexOutOfBoundsException(){
// ArrayIndexOutOfBoundsException
/*
* int[] arr = new int[3];
* System.out.println(arr[5]);
*/
// StringIndexOutOfBoundsException
String s = "123";
System.out.println(s.charAt(5));
}
// ClassCastException
@Test
public void testClassCastException(){
// 类强转异常
Object obj = new Object();
String str = (String)obj;
}
// NumberFormatException
@Test
public void testNumberFormatException(){
// NumberFormatException
String str = "abc";
Integer.parseInt(str);
}
// InputMismatchException
@Test
public void testInputMismatchException(){
// 当输入字符不为数字时报错
Scanner sc = new Scanner(System.in);
System.out.println(sc.nextInt());
sc.close();
}
// ArithmeticException
@Test
public void testArithmeticException(){
// 除数为0,出现异常
System.out.println(5 / 0);
}
// ---------------------------编译时异常---------------------------
@Test
public void test(){
// 编译时异常在使用javac进行编译时便会报错,不对这类异常进行处理就无法编译生成.class文件
File file = new File("Exception.txt");
// Unhandled exception type FileNotFoundException
FileInputStream fis = new FileInputStream(file);
// Unhandled exception type IOException
int data = fis.read();
while(data != -1){
System.out.println((char)data);
data = fis.read();
}
fis.close();
}
}
throw 与 throws 的区别
throw:生成一个异常对象,并抛出,使用在方法内部(手动抛异常)
throws:处理异常的方式,使用在方法声明处的末尾
这两者之间是递进关系,使用 throw 手动抛出异常(或自动抛出的异常),然后使用 throws(或 try-catch)对抛出的异常进行处理