【java基础】异常处理

我是 啤酒就辣条,一个Java。
学而时习之,不亦说乎?希望通过博客的形式,总结、分享,梳理自己、帮助他人。
另外,啤酒就辣条,味道不错哦~

异常的分类

异常是阻止当前方法或作用域继续执行的问题。异常分为两种,一种是不可控的Error,它有由环境产生的错误,代码层面无法解决的问题,比如VirtualMachineError(虚拟机资源枯竭时报错)。还有一种是由你代码逻辑产生的Exception,是需要通过完善代码避免的错误,比如说NullPointerException(引用没有具体指向的时候报错)ErrorException有一个共同的父类Throwable

对于Exception可以进一步分为uncheckedchecked,即继承了RuntimeException的是unchecked,典型的有NullPointerException;没有继承RuntimeException的是checked,典型的有IOExceptionunchecked无需在代码里显示的处理,而checked需要。

异常的处理

异常处理可以此时处理或者抛给调用者

此时处理

可以通过try{}catch(){}进行当前处理。

public class ExceptionTest {
    public static void main(String[] args) {
        try {
            throw new IOException();
        }catch (IOException e){
            System.out.println("这里可以处理一些异常");
        }finally {
            System.out.println("这里无论有没有捕获异常,都可以执行");
        }
    }
}

抛给调用者

public class ExceptionTest {
    public static void main(String[] args) {
        try {
            getException();
        }catch (Exception e){
            System.out.println("这里可以处理一些异常");
        }finally {
            System.out.println("这里无论有没有捕获异常,都可以执行");
        }
    }
    private static void getException() throws Exception{
        throw new Exception("我把错误给调用者");
    }
}

catch错误的顺序

捕获异常可以多加几个catch,按顺序尝试是否可以处理

public class ExceptionTest {
    public static void main(String[] args) {
        try {
            throw new IOException();
        }catch (IOException e){
            System.out.println("捕获IOException,我会打印");
        } catch (Exception e){
            System.out.println("上面那个catch无法捕获,那我来试试");
        }finally {
            System.out.println("这里无论有没有捕获异常,都可以执行");
        }
    }
}
原文地址:https://www.cnblogs.com/pjjlt/p/12408037.html