Java的异常处理学习(学不会版~~)

Error与Exception的区别

Error是程序无法处理的错误,比如OutMemoryError,ThreadDeath等,这些异常发生的时候,Java虚拟机(JVM)一般会选择线程终止。此类异常是程序猿的致命异常。
Exception是程序本身可以处理的异常,这种异常分为两大类运行时异常和非运行时异常,程序中应该尽可能去处理这种异常。

Exception类的继承关系

image.png

运行时异常和非运行时异常的区别

运行时异常都是RuntimeException类及其子类,如NullPointerException、IndexOutOfBoundsException等,这些异常一般是由程序逻辑错误引起的,程序员应当从逻辑的角度尽量避免此类异常的发生。
非运行时异常时RunTimeException以外的异常,类型上都属于Exception类及其子类。从程序语法角度讲,是必须处理的异常,如果不处理程序就不能编译通过。如IOException,SQLException等以及用户自定义的Exception异常,这些是检查型异常。一般情况下不自定义检查型异常。

内置异常类(积累ing)

非检查性异常

异常描述

检查性异常

异常描述

内置异常方法(积累ing)

方法说明

捕获异常

package org.example;

import java.util.*;

public class Main {
    public static void foo(){
        int[] array = new int[5];
        for (int i = 0; i < array.length; i ++){
            array[i]= i;//初始化数组
        }
        Scanner sc = new Scanner(System.in);
        int k = sc.nextInt();
        int x = sc.nextInt();
        try{
            array[k] /= x;
        }catch (ArithmeticException e){
            System.out.println("除以零啦!");
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println("数组越界啦!");
        }finally {
            //不管有没有异常都会执行的代码
            for(int i = 0; i < 5; i ++){
                System.out.printf("array[%d] = %d\n",i,array[i]);
            }
        }
    }
    public static void main(String[] args) {
        foo();
    }
}
/*
输出结果:
-1 0
数组越界啦!
array[0] = 0
array[1] = 1
array[2] = 2
array[3] = 3
array[4] = 4

3 0
除以零啦!
array[0] = 0
array[1] = 1
array[2] = 2
array[3] = 3
array[4] = 4
*/

抛出异常(没学明白~~)

throw:在函数内抛出一个异常
throws:在函数定义时抛出一些可能的异常
检查型异常必须被捕获或者抛出(这是两种处理异常的方法)

package org.example;

import java.io.IOException;
import java.util.*;

public class Main {
    private static void foo(){
        Scanner sc = new Scanner(System.in);
        int x = sc.nextInt();
        if(x == 1){
            try {
                throw new IOException("找不到文件!!");
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }
    public static void main(String[] args) {
        foo();
    }
}
/*
输出结果
1
找不到文件!!

*/

try-with-resources(也没听懂~~)

jdk7之后,java新增的try-with-resources语法糖用来打开资源,并且可以确保在语句执行完之后关闭所有资源。
try用来申明和实例化资源,catch用来处理关闭资源所引发的异常。

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值