异常
异常就是程序非正常运行时的报错,不正常就是异常。
异常分类
通常分为两类:
Error
:错误。通常是Java虚拟机无法解决的严重问题。如:JVM系统内部错误、资源耗尽等严重情况。比如:StackOverflowError
和OOM-->OutOfMemory
。
一般不编写针对性的代码进行处理。
Exception
:其它因编程错误或偶然的外在因素导致的一般性问题, 可以使用针对性的代码进行处理。
异常体系结构
父类为Throwable
。
图中蓝色的是非受检异常(unchecked)或称运行时异常。
红色是受检异常(checked)或称编译时异常,会在编译时进行报错。

常见异常
Exception
编译时异常(checked)
- IOException
- FileNotFoundException
- ClassNotFoundException
运行时异常(unchecked,RuntimeException)
-
NullPointerException–>空指针异常
-
ArrayIndexOutOfBoundsException–>数组越界异常
-
ClassCastException–>类转换异常
-
NumberFormatException–>数值格式异常
-
InputMismatchException–>输入不匹配异常
-
ArithmeticException–>算术异常
示例:
import java.util.Scanner; import org.junit.Test; public class ExceptionTest { @Test public void test1(){ //NullPointerException int[] arr = new int[5]; arr = null; System.out.println(arr[0]); } @Test public void test2(){ //ArrayIndexOutOfBoundsException int[] arr = new int[]{1,2,3}; System.out.println(arr[3]); } @Test public void test3(){ //ClassCastException Object s = "abc"; int i = (int)s; } @Test public void test4(){ //NumberFormatException String s = "123"; int i = Integer.parseInt(s); System.out.println(i); } @Test public void test5(){ //InputMismatchException System.out.println("please input"); Scanner scanner = new Scanner(System.in); int i = scanner.nextInt(); System.out.println(i); scanner.close(); } @Test public void test6(){ //ArithmeticException System.out.println(2 / 0); } }
异常处理
抓抛模型
过程一:“抛”:程序在正常执行的过程中,一旦出现异常,就会在异常代码处生成一个对应异常类的对象。并将此对象抛出。
一旦抛出对象以后,其后的代码就不再执行。
过程二:“抓”:可以理解为异常的处理方式:
-
try-catch-finally
-
throws
try-catch-finally
这个结构可以抓住当前异常进行处理。
try{
//可能出现异常的代码
}catch(异常类型1 变量名1){
//处理异常的方式1
}catch(异常类型2 变量名2){
//处理异常的方式2
}catch(异常类型3 变量名3){
//处理异常的方式3
}
....
finally{
//一定会执行的代码
}
-
finally是可选的。
-
使用try将可能出现异常代码包装起来,在执行过程中,一旦出现异常,就会生成一个对应异常类的对象,根据此对象的类型,去catch中进行匹配
-
一旦try中的异常对象匹配到某一个catch时,就进入catch中进行异常的处理。一旦处理完成,就跳出当前的try-catch结构(在没有写finally的情况)。继续执行其后的代码
-
catch中的异常类型如果没有子父类关系,则谁声明在上,谁声明在下无所谓。
catch中的异常类型如果满足子父类关系,则要求子类一定声明在父类的上面。否则,会报错
-
常用的异常对象处理的方式:
String getMessage()
printStackTrace()
-
在try结构中声明的变量,再出了try结构以后,就不能再被调用
-
try-catch-finally结构可以嵌套
体会
-
使用try-catch-finally处理编译时异常,使得程序在编译时不再报错,但是运行时仍可能报错。相当于我们使用try-catch-finally将一个编译时可能出现的异常,延迟到运行时出现。
-
开发中,由于运行时异常比较常见,所以我们通常就不针对运行时异常编写try-catch-finally了
而针对于编译时异常,我们说一定要考虑异常的处理。(对于这一点,你可以先往下看,到finally结束时再次回顾。)
finally的二三事
finally
中声明的是一定会被执行的代码。即使catch中又出现异常了,或者try中有return语句,catch中有return语句等情况下,也会被强制在方法返回前执行。- 像数据库连接、输入输出流、网络编程Socket等资源,JVM是不能自动的回收的,我们需要自己手动的进行资源的释放。此时的资源释放,就需要声明在finally中。
@Test
public void test1(){
FileInputStream fis = null;
try {
File file = new File("hello.txt");
//当文件存在,程序正常运行;文件不存在,打印异常,两种情况finally都会执行。
fis = new FileInputStream(file);
int data = fis.read();
while (data != -1) {
System.out.println((char)data);
data = fis.read();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
System.out.println("程序结束啦,现在finally。。。");
//如果是异常到这里,fis应该是空的,所以要判断一下
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
写完这个程序你会发现,如果是编译时异常,我们使用try-catch将其延长到运行时才进行报错,或者说,程序强制要求我们进行处理,就拿文件处理来说,我们预见一定会有找不到文件的情况,并且要求处理。而如果是运行时异常,则程序并不报错,只有运行起来我们才知道有bug。
这种情况下,我们会发现,捕捉了运行时异常并进行报错,实际和程序自己进行报错没什么区别。所以我们才不针对运行时异常编写try-catch-finally(一般情况下)
throws
这个结构只能将异常进行抛出。不能处理。
public void method() throws IOException{ }
"throws + 异常类型"写在方法的声明处。指明此方法执行时,可能会抛出的异常类型。一旦当方法体执行时,出现异常,仍会在异常代码处生成一个异常类的对象,此对象满足throws后异常类型时,就会被抛出。异常代码后续的代码,就不再执行!
二者的区别
try-catch-finally:真正的将异常给处理掉了。
throws的方式只是将异常抛给了方法的调用者。 并没有真正将异常处理掉。
如何选择
-
如果父类中被重写的方法没有throws方式处理异常,则子类重写的方法也不能使用throws,意味着如果子类重写的方法中有异常,必须使用try-catch-finally方式处理。
-
执行的方法a中,先后又调用了另外的几个方法,这几个方法是递进关系执行的。我们建议这几个方法使用throws的方式进行处理。而执行的方法a可以考虑使用try-catch-finally方式进行处理。
手动抛出异常
生成官方异常对象
throw
关键字生成异常对象
public class Student {
private int id;
public void regester(int id){
if (id > 0) {
this.id = id;
} else {
throw new RuntimeException("您输入的数据非法!");
//自己抛出一个异常,并且传入错误信息
}
}
@Override
public String toString() {
return "Student [id=" + id + "]";
}
public static void main(String[] args) {
Student s1 = new Student();
s1.regester(-1);
System.out.println(s1);
}
}
自定义异常类型
分三步:
- 继承异常体系
- 给出唯一标识
serialVersionUID
- 提供重载的构造器
public class MyException extends RuntimeException{
static final long serialVersionUID = -338751699363429948L;
public MyException() {
super();
}
public MyException(String message) {
super(message);
}
}
之后当作正常的异常进行抛出就行了
练习
编写应用程序EcmDef.java,接收命令行的两个参数,要求不能输入负数,计算两数相除。
对数据类型不一致NumberFormatException
、缺少命令行参数ArrayIndexOutOfBoundsException
、除0ArithmeticException
及输入负数EcDef 自定义的异常
进行异常处理。
提示:
- 在主类(EcmDef)中定义异常方法(ecm)完成两数相除功能。
- 在main()方法中使用异常处理语句进行异常处理。
- 在程序中,自定义对应输入负数的异常类(EcDef)。
- 运行时接受参数 java EcmDef 20 10 //args[0]=“20” args[1]=“10”
- Interger类的static方法
parseInt(String s)
将s转换成对应的int值。
如:int a=Interger.parseInt(“314”); //a=314;
public class EcmDef {
public static void main(String[] args) {
try {
int i = Integer.parseInt(args[0]);
int j = Integer.parseInt(args[1]);
System.out.println(ecm(i, j));
} catch (NumberFormatException e) {
System.out.println("数值转换异常!");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("缺少参数!");
} catch (ArithmeticException e) {
System.out.println("除零!");
} 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;
}
}
public class EcDef extends RuntimeException{//若继承Exception,就是编译时异常
static final long serialVersionUID = -70348972321766939L;
public EcDef() {}
public EcDef(String message) {super(message);}
}
我这里写的是一个运行时异常,所以没有进行异常处理。
但如果你写的是编译时异常,就要选择进行处理
总结
