1.异常的介绍和作用
1.异常的种类繁多,Java规定了一种异常的体系,如图:
2.throw关键字和throws关键字(异常的抛出)
1.throw关键字
一般格式
修饰符 返回值类型 方法名() throws 异常类名 {}
代码演示
public static int test(int[] array,int pos){
if (array==null){
throw new NullPointerException("数组为空");
}
if(pos<0||pos>=array.length){
throw new ArithmeticException("数组下标越界");
}
return array[pos];
}
若输入数组为空
相同的,若数组下标越界,则显示:ArithmeticException: 数组下标越界。
注意事项:
System.out.println("!!!!!");语句,如果在main中出现空数组,这哥语句就不会执行,就算之后出现了数组越界的异常,也不会执行。)
2.throws关键字
一般格式
修饰符 返回值类型 方法名(参数列表) [throws 异常的类型] {
if (判断条件) {
throw new 异常对象("异常的原因");
}
代码演示
public static int test(int[]array,int pos)throws NullPointerException,ArithmeticException{
if (array==null){
throw new NullPointerException("数组为空");
}
System.out.println("!!!!!");
if(pos<0||pos>=array.length){
throw new ArithmeticException("数组下标越界");
}
System.out.println("!!!!!");
return array[pos];
}
throws与throw实质上差别不大,差别在与throws在实现的格式上throws后要跟上异常的类型
区别:
3.try-catch关键字(异常的捕获)
格式,代码演示
try{可能出现异常的代码
}catch(异常类型 e){
}catch(异常类型 e){
}........后续代码
代码演示
try {
int[] array = null;
test1();
}catch (NullPointerException e){
e.printStackTrace();
}catch (ArithmeticException e){
e.printStackTrace();
}catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
}
4.异常处理的流程
1.throw的运行流程
throw中含中含有多个异常时,代码会执行到遇到异常时,一旦抛出异常后,后面的代码就不会继续执行,包括后面的异常也不会继续抛出。
public static int test(int[] array,int pos){
System.out.println("!!!!!");
if (array==null){
throw new NullPointerException("数组为空");
}//若在main中出现了为空的代码,结果就为“!!!!!”加上“数组为空”
System.out.println("!!!!!");
if(pos<0||pos>=array.length){
throw new ArithmeticException("数组下标越界");
}//若在main中出现了下标越界的代码,结果就为“!!!!!”加上“数组下标越界”
System.out.println("!!!!!");
return array[pos];
}
2.try-catch的运行流程
在try-catch捕获异常在时候存在着多种情况:
1)try中的数据未出现异常
因为try中未出现异常,所以可以认为代码不会执行catch阶段,而直接往后执行。
2)try中的数据出现异常,但catch中没有与之相应的捕获类型
没有相应的捕获类型,就无法捕获异常,从而导致代码不会往后执行。
3)try中的数据出现异常,catch中有与之相应的捕获类型
此时异常就会被成功捕获并处理,之后的代码也会继续执行。注意的是,如果try中出现多个异常,try-catch只会捕获第一个异常。如果要捕获多个异常,就要写多个try-catch语句。
3)finally关键字
finally关键字主要是运用在try-catch语句中,在写程序时,有些特定的代码,不论程序是否发生异
常,都需要执行,比如程序中打开的资源:网络连接、数据库 连接、IO流等,在程序正常或者异
常退出时,必须要对资源进进行回收。另外,因为异常会引发程序的跳转,可能 导致有些语句执
行不到,finally就是用来解决这个问题的。
而且,不论在try-catch语句中出现上述哪一种情况,finally中的内容都会执行。
还有一种情况:
public static int test3(){
try {
return 10;
}finally {
return 20;
}
}
public static void main(String[] args) {
System.out.println(test3());
}//可以猜猜此处的执行结果为什么?
结果为:20
谢谢观看,如果觉得博主写的还ok,别完了点赞,这对我真的很重要!!!