基础:异常及其处理
一、异常概述与异常体系结构
1.定义
在Java语言中,将程序执行中发生的不正常情况称为“异常”。 (开发过程中的语法错误和逻辑错误不是异常)
2.分类
(1) Error:Java虚拟机无法解决的严重问题。如:JVM系统内部错误、资源耗尽等严重情况。比如:StackOverflowError(栈溢出)和OOM(OutOfMemoryError,堆溢出)。一般不编写针对性的代码进行处理。
(2) Exception: 其它因编程错误或偶然的外在因素导致的一般性问题,可以使用针对性的代码进行处理。例如:
- 空指针访问
- 试图读取不存在的文件
- 网络连接中断
- 数组角标越界
3.异常体系结构
捕获错误最理想的是在编译期间,但有的错误只有在运行时才会发生。比如:除数为0,数组下标越界等。
Exception异常又分为:编译时异常(受检(checked)异常)和运行时异常(非受检(unchecked)异常)。
java.lang.RuntimeException类及它的子类都是运行时异常。
4.常见异常举例
运行时异常
- NullPointerException:空指针异常
@Test
public void test1(){
// int[] arr = null;
// System.out.println(arr[2]);
String str = "abc";
str = null;
System.out.println(str.charAt(0));
}
- ArrayIndexOutOfBoundsException:数组角标越界异常
@Test
public void test2(){
int[] arr = new int[10];//0-9
System.out.println(arr[11]);
System.out.println(arr[10]);
}
- StringIndexOutOfBoundsException::字符串角标越界
public void test2(){
String str = "abc";
System.out.println(str.charAt(3));
}
- ClassCastException:类型转换异常
@Test
public void test3(){
Object obj = new Date();
String str = (String)obj;
}
- NumberFormatException:数字格式异常
public static void main(String[] args) {
// 将字符串“it”转换为Integer类型的,当然会报数字格式异常啦
System.out.println(Integer.parseInt("it"));
}
- 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);
}
编译时异常
在编译前代码会打叉
二、异常处理机制
一.try-catch-finally
1.理解
Java提供的是异常处理的抓抛模型。
“抛” :程序在正常执行的过程中,一旦出现异常,就会在异常代码处生成一个对应异常类的对象。并将此对象抛出,该异常对象将被提交给Java运行时系统。一旦对象抛出后,其后的代码就不再执行。
“抓” :可以理解为异常的处理方式
2.语句格式
try{
//可能出现异常的代码
}
catch(异常类型 变量名){
//异常处理
}
finally {
//一定会执行的代码
}
3.举例
1:ArrayIndexOutOfBoundsException:
数组越界 -->>指使用非法索引访问数组。索引为负值或大于或等于数组的大小。
public class IndexOutExp {
public static void main(String[] args) {
String friends[] = {
"lisa", "bily", "kessy" };
try {
for (int i = 0; i < 5; i++) {
System.out.println(friends[i]);
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("index err");
}
System.out.println("\nthis is the end");
} }
程序IndexOutExp.java运行结果:java IndexOutExp
lisa
bily
kessy
index err
this is the end
2:ArithmeticException
除0发生的算术异常
public class DivideZero1 {
int x;
public static void main(String[] args) {
int y;
DivideZero1 c = new DivideZero1();
try {
y = 3 / c.x;
} catch (ArithmeticException e) {
System.out.println("divide by zero error!");
}
System.out.println("program ends ok!");
} }
程序DivideZero1运行结果:java DivideZero1
divide by zero error!
program ends ok!
4.注意点
- 一旦try中的异常对象匹配到某一个catch时,就进入catch中进行异常的处理。一旦处理完成,就跳出当前的
try-catch结构(在没有写finally的情况)。继续执行其后的代码 - catch中的异常类型如果没有子父类关系,则谁声明在上,谁声明在下无所谓。
catch中的异常类型如果满足子父类关系,则要求子类一定声明在父类的上面。否则,报错
例题中:Exception是NullPointerException,NumberFormatException的父类,则需要放在后面
@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("出现数值转换异常了,不要着急....");
}catch(NullPointerException e){
System.out.println("出现空指针异常了,不要着急....");
}catch(Exception e){
System.out.println("出现异常了,不要着急....");
}
System.out.println("hello-----2");
}
- 在catch中常用的异常对象处理的方式: ① String getMessage() ② printStackTrace()
注意:两种方式输出语句和打印结果的异同
- 在try结构中声明的变量,再出了try结构以后,就不能再被调用
- 如需使用,可以声明在外部,在内部使用。
举例:
解决方案:声明在外部,内部使用
- finally中声明的是一定会被执行的代码
注意:如果finally中的代码也可能出现异常,就也需要在finally中try-catch
二.throws + 异常类型
1.理解
“throws + 异常类型” 写在方法的声明处,指明此方法执行时,可能会抛出异常类型。一旦当方法体执行时,出现异常,仍会在异常代码处生成一个异常类的对象,此对象满足throws后异常类型时,就会被抛出。异常代码后续的代码就不再执行。
try-catch-finally 真正将异常处理掉了,但是throws 的方法只是将异常抛给了方法的调用者,并没有真正将异常处理掉。
2.格式举例
public void readFile(String file) throws FileNotFoundException {
……
// 读文件的操作可能产生FileNotFoundException类型的异常
FileInputStream fis = new FileInputStream(file);
..……
}
3.重写方法声明抛出异常的原则
子类重写方法不能抛出比被父类被重写的方法范围更大的异常类型。
如:
public class A {
public void methodA() throws IOException {
……
} }
public class B1 extends A {
public void methodA() throws FileNotFoundException {
……
} }
public class B2 extends A {
public void methodA() throws Exception {
//报错
……
} }
这就是说,父类中被重写的方法没有throws方式处理异常,则子类重写的方法也不能使用throws。意味着若子类重写的方法中有异常,必须使用try-catch-finally 方式处理。
三.开发中如何选择这两种处理机制
- (1)父类中被重写的方法没有throws方式处理异常,则子类重写的方法也不能使用throws。意味着若子类重写的方法中有异常,必须使用try-catch-finally 方式处理。
- (2) 执行的方法a中,先后又调用了另外的几个方法,这几个方法是递进关系执行的。我们建议这几个方法使用throws的方式进行处理。而执行的方法a可以考虑使用try-catch-finally 方式处理。
三、手动抛出异常
1:自定义异常类
class Student{
private int id;
public void regist(int id) throws Exception {
if(id > 0){
this.id = id;
}else{
//手动抛出异常对象
// throw new RuntimeException("您输入的数据非法!");
// throw new Exception("您输入的数据非法!");
throw new MyException("不能输入负数");
}
}
@Override
public String toString() {
return "Student [id=" + id + "]";
}
}
四、用户自定义异常类
1.理解
用户自定义异常类MyException,用于描述数据取值范围错误信息。用户自己的异常类必须继承现有的异常类。
class MyException extends Exception {
static final long serialVersionUID = 13465653435L;
private int idnumber;
public MyException(String message, int id) {
super(message);
this.idnumber = id;
}
public int getId() {
return idnumber;
}
}
2.如何自定义异常类
-
继承于现有的异常结构:RuntimeException、 Exception;
-
提供全局常量(序列号,自己独有的):serialVersionUID
-
提供重载的构造器
五、综合练习
- 编写应用程序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;
自定义异常类(EcDef)
//自定义异常类
public class EcDef extends Exception {
static final long serialVersionUID = -33875164229948L;//序列号,可任意改,EcDef独有即可
public EcDef() {
}
public EcDef(String msg) {
super(msg);
}
}
主类(EcmDef)
public class EcmDef {
public static void main(String[] args) {
//用命令行参数
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;
}
}
六、常见问题
1:总结
2:throw 和 throws区别
- throw 表示抛出一个异常类的对象,生成异常对象的过程。声明在方法体内。
- throws 属于异常处理的一种方式,声明在方法的声明处。
3:如何看待代码中的编译时异常和运行时异常?
- 体会1:使用try-catch-finally处理编译时异常,是得程序在编译时就不再报错,但是运行时仍可能报错。相当于我们使用try-catch-finally将一个编译时可能出现的异常,延迟到运行时出现。
- 体会2:开发中,由于运行时异常比较常见,所以我们通常就不针对运行时异常编写try-catch-finally了。针对于编译时异常,我们说一定要考虑异常的处理。
- 看图体会(RuntimeException运行时异常,Exception:编译时异常)
RuntimeException运行时异常
Exception:编译时异常
public class StudentTest{
public static void main(String[] args) {
try {
Student s = new Student();
s.regist(-1001);
System.out.println(s);
} catch (Exception e) {
// TODO Auto-generated catch block
//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 {
//手动抛出异常
//throw new RuntimeException("您输入的数据非法!");
throw new Exception("您输入的数据非法!");//体现生成一个异常对象
}
}
}
七、面试题
Java中的异常处理机制的简单原理和应用
- 当JAVA程序违反了JAVA的语义规则时,JAVA虚拟机就会将发生的错误表示为一个异常。
- 违反语义规则包括2种情况。
- 一种是JAVA类库内置的语义检查。例如数组下标越界,会引发IndexOutOfBoundsException;访问null的对象时会引发NullPointerException。
- 另一种情况就是JAVA允许程序员扩展这种语义检查,程序员可以创建自己的异常,并自由选择在何时用throw关键字引发异常。所有的异常都是java.lang.Thowable的子类。
try {}里有一个return语句,那么紧跟在这个try后的finally {}里的code会不会被执行,什么时候被执行,在return前还是后?
- 答:会执行,在return前执行