7.异常处理
7.1异常概述与异常体系结构
7.1.1异常概述
异常:在Java语言中,将程序执行中发生的不正常情况称为“异常(开发过程中的语法错误和逻辑错误不是异常)
- eg:用户输入格式不正确、要读的文件是否存在、网络是否正常
Java程序在执行过程中所发生的异常事件可分为两类:
- Error:Java虚拟机无法解决的严重问题。一般不编写针对性的代码进行处理。
- eg:JVM系统内部错误、资源耗尽等严重情况。比如:StackOverflowError(栈溢出)和OOM(OutOfMemoryError,堆溢出)。
- Exception:其它因编程错误或偶然的外在因素导致的一般性问题,可以使用针对性的代码进行处理。
- eg:空指针访问、试图读取不存在的文件、网络连接中断、数组角标越界
7.1.2异常体系结构
java.lang.Throwable
|----java.lang.Error:一般不编写针对性的代码进行处理。
|----java.lang.Exception:可以进行异常的处理
|----编译时异常(checked),部分如下
|----IOException
|----FileNotFoundException
|----ClassNotFoundException
|----运行时异常(unchecked),部分如下
|----Nul1PointerException
|----ArrayIndexoutOfBoundsException
|----ClassCastException
|----NumberFormatException
|----InputMismatchException
|----ArithmeticException
7.2常见异常
面试题:常见的异常都有哪些?举例说明
package com.atguigu.classes.test;
/*
* java.lang.Throwable
|----java.lang.Error:一般不编写针对性的代码进行处理。
|----java.lang.Exception:可以进行异常的处理
|----编译时异常(checked),部分如下
|----IOException
|----FileNotFoundException
|----ClassNotFoundException
|----运行时异常(unchecked),部分如下
|----Nul1PointerException
|----ArrayIndexoutOfBoundsException
|----ClassCastException
|----NumberFormatException
|----InputMismatchException
|----ArithmeticException
*/
import java.io.File;
import java.io.FileInputStream;
import java.util.Scanner;
import org.junit.Test;
public class ExceptionTest {
public static void main(String[] args) {
//java.lang.StackOverflowError(栈溢出)
//main(args);
//java.lang.OutOfMemoryError(堆溢出)
//String[] strs=new String[1024*1024*1024];
}
//**********************************************以下是编译时异常
@Test
public void test7(){
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();
}
//**********************************************以下是运行时异常
//Nul1PointerException空指针异常
@Test
public void test1(){
int[] i=null;
System.out.println(i[0]);
}
//ArrayIndexoutOfBoundsException数组索引越界异常
@Test
public void test2() {
String strs="abc";
System.out.println(strs.charAt(3));
}
//ClassCastException类型转换异常
@Test
public void test3(){
Object o=new String();
int i=(int)o;
}
//NumberFormatException数值转换异常
@Test
public void test4(){
String str="123c";
int i=Integer.parseInt(str);
}
//InputMismatchException输入类型不匹配异常
@Test
public void test5() {
Scanner scan=new Scanner(System.in);
System.out.println(scan.nextInt());
}
//ArithmeticException算术异常
@Test
public void test6() {
int a=3;
int b=0;
System.out.println(a/b);
}
}
编译时异常:执行javac.exe命名时,可能出现的异常
运行时异常:执行java.exe命名时,出现的异常
7.3异常处理机制一: try-catch-finally
7.3.1概述
在编写程序时,经常要在可能出现错误的地方加上检测的代码,如进行x/y运算时,要检测分母为0,数据为空,输入的不是数据而是字符等。过多的if-else分支会导致程序的代码加长、臃肿,可读性差。因此采用异常处理机制。
Java异常处理
Java采用的异常处理机制,是将异常处理的程序代码集中在一起,与正常的程序代码分开,使得程序简洁、优雅,并易于维护。
Java提供的是异常处理的抓抛模型。
- 过程一:“抛”:程序在正常执行的过程中,一旦出现异常,就会在异常代码处生成一个对应异常类的对象。并将此对象抛出。一旦抛出对象以后,其后的代码就不再执行.
- 过程二:“抓”:可以理解为异常的处理方式:①try-catch-finally ②throws
7.3.2try-catch-finally的使用
/*
try{
//可能出现异常的代码
}catch(异常类型1 变量名1){
//处理方式1
}catch(异常类型2 变量名2){
//处理方式1
}catch(异常类型3 变量名3){
//处理方式1
}
......
finally{
//一定会执行的代码
}
说明:
- finally是可选的。
- finally中声明的是一定会被执行的代码。即使catch中又出现异常了,try中有return语句,catch中有return语句等情况,也会在return之前执行finally中的语句
- 使用try将可能出现异常代码包装起来,在执行过程中,一旦出现异常,就会生成一个对应异常类的对象,根据此对象的类型,去catch中进行匹配,不会执行try中异常语句后面的代码。因此若在try中有return语句,一定要在catch中也加上return语句
- 一旦try中的异常对象匹配到某一个catch时,就进入catch中进行异常的处理。一旦处理完成,就会跳出当前的try-catch结构,不再执行剩下的catch(在没有写finally的情况下)。但是会继续执行try-catch结构后面的语句
- catch中的异常类型如果没有子父类关系,则谁声明在上,谁声明在下无所谓。
catch中的异常类型如果满足子父类关系,则要求子类一定声明在父类的上面。否则,报错 - 常用的异常对象处理的方式: ①System.out.println(e.getMessage()); ②e.printstackTrace() 后者的异常信息更详细,包括了前者
- .在try或catch中声明的变量,再出了try结构以后,就不能再被调用
- 体会:使用try-catch-finally处理编译时异常,是得程序在编译时就不再报错,但是运行时仍可能报错。
相当于我们使用try-catch-finally将一个编译时可能出现的异常,延迟到运行时出现。 - 像数据库连接、输入输出流、网络编程Socket等资源,JVM是不能自动的回收的,我们需要自己手动的进行资源的释放。此时的资源释放,就需要声明在finally中。
- 开发中,由于运行时异常比较常见,所以我们通常就不针对运行时异常编写try-catch-final.ly了。
针对于编译时异常,我们说一定要考虑异常的处理。|
package com.atguigu.classes.test;
/*
* java.lang.Throwable
|----java.lang.Error:一般不编写针对性的代码进行处理。
|----java.lang.Exception:可以进行异常的处理
|----编译时异常(checked),部分如下
|----IOException
|----FileNotFoundException
|----ClassNotFoundException
|----运行时异常(unchecked),部分如下
|----Nul1PointerException
|----ArrayIndexoutOfBoundsException
|----ClassCastException
|----NumberFormatException
|----InputMismatchException
|----ArithmeticException
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import org.junit.Test;
public class ExceptionTest {
public static void main(String[] args) {
//java.lang.StackOverflowError(栈溢出)
//main(args);
//java.lang.OutOfMemoryError(堆溢出)
//String[] strs=new String[1024*1024*1024];
}
//**********************************************以下是编译时异常
@Test
public void test7(){
//如果在try中声明的话finally访问不到fis,
//并且要给初始化值,否则会报错。因为如果hello.txt不存在,new FileInputStream就会抛出异常,不会执行try中剩下的语句
FileInputStream fis =null;
try {
File file = new File( "hello.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)//需要判断fis是否为空,若不判断,则当fis为null时fis.close会报错,且不是IOException,而是空指针异常
fis.close();//这句需要处理异常,否则会报错
} catch (IOException e) {
e.printStackTrace();
}
}
}
//**********************************************以下是运行时异常
//Nul1PointerException空指针异常
@Test
public void test1(){
int[] i=null;
System.out.println(i[0]);
}
//ArrayIndexoutOfBoundsException数组索引越界异常
@Test
public void test2() {
String strs="abc";
System.out.println(strs.charAt(3));
}
//ClassCastException类型转换异常
@Test
public void test3(){
Object o=new String();
int i=(int)o;
}
//NumberFormatException数值转换异常
@Test
public void test4(){
String str="123c";
Integer.parseInt(str);
}
//InputMismatchException输入类型不匹配异常
@Test
public void test5() {
Scanner scan=new Scanner(System.in);
System.out.println(scan.nextInt());
}
//ArithmeticException算术异常
@Test
public void test6() {
int a=3;
int b=0;
System.out.println(a/b);
}
}
7.4异常处理机制二: throws
7.4.1throws使用
"throws +异常类型"写在方法的声明处。指明此方法执行时,可能会抛出的异常类型。
一旦当方法体执行时,出现异常,仍会在异常代码处生成一个异常类的对象,此对象满足throws后异常类型时,就会被抛出。
异常代码后续的代码,就不再执行!
package com.atguigu.classes.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ExceptionTest2 {
public static void main(String[] args) {//再往上抛就是JVM了,一般不往上抛了,在这里就进行处理
try {
method2();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void method2() throws FileNotFoundException,IOException{//抛异常给调用它的函数,也可以这两个异常的父类IOException
method1();
}
public static void method1() throws FileNotFoundException,IOException{//抛异常给调用它的函数
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();
}
}
7.5两种异常处理机制的区别
try-catch-finally:真正的将异常给处理掉了。
throws的方式只是将异常抛给了方法的调用者。并投有真正将异常处理掉。
方法重写的规则之—:
子类重写的方法抛出的异常类型不大于父类被重写的方法抛出的异常类型
开发中如何选择使用try-catch-finally 还是使用throws?
- 3.1如果父类中被重写的方法没有throws方式处理异常,则子类重写的方法也不能使用throws,意味着如果
子类重写的方法中有异常,必须使用try-catch-finally方式处理。 - 3.2执行的方法a中,先后又调用了另外的几个方法,这几个方法是递进关系执行的。我们建议这几个方法使用throws
的方式进行处理。而执行的方法a可以考虑使用try-catch-finally方式进行处理。
7.5手动抛出异常: throw
关于异常对象的产生: ①系统自动生成的异常对象 ②手动的生成—个异常对象,并抛出(throw)
package com.atguigu.classes.test;
public class ExceptionTest3 {
public static void main(String[] args) {
try {
TestStu test = new TestStu();
test.regist(-1001);
System.out.println(test);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class TestStu{
private int id;
public void regist(int id) throws Exception{
if(id>0) {
this.id=id;
}else {
//这样处理id<0的情况,System.out.println(test)仍然会执行
//System.out.println("输入的数据非法");
//当输入数据非法时候应该打断程序,不再执行后面的,应该用throw手动抛异常给上一级
//throw运行时异常时ExceptionTest3不处理该异常、regist声明处不throws,不会报错,因为这是运行时异常,可以不处理
//throw new RuntimeException("输入的数据非法");
//此时需要ExceptionTest3处理该异常,regist声明处throws,否则报错
throw new Exception("输入的数据非法");
}
}
@Override
public String toString() {
return "TestStu [id=" + id + "]";
}
}
7.6用户自定义异常类
package com.atguigu.classes.test;
/*
* 如何自定义异常类?
* 1.继承于现有的异常结构: RuntimeException . Exception
* 2.提供全局常量: serialVersionUID
* 3.提供重载的构造器
*/
public class MyException extends RuntimeException{
static final long serialVersionUID = -7034897193246939L;
public MyException(){}
public MyException(String msg){
super(msg);
}
}
7.7throw和throws区别
Java提供的是异常处理的抓抛模型。
- 过程一:“抛”:程序在正常执行的过程中,一旦出现异常,就会在异常代码处生成一个对应异常类的对象。并将此对象抛出。一旦抛出对象以后,其后的代码就不再执行.
- 关于异常对象的产生: ①系统自动生成的异常对象 ②手动的生成—个异常对象,并抛出(throw)
- 过程二:“抓”:可以理解为异常的处理方式:①try-catch-finally ②throws
因此throw处于异常的生成阶段:手动抛出异常对象,throws是异常的一种处理方式:声明方法可能要抛出的各种异常类