java基础篇之异常处理

概述
  • java把所有非正常的情况分为两类,异常(Exception)和错误(Error),他们都继承自Throwable类
    在这里插入图片描述
  • Error错误,一般指jvm相关问题,系统崩溃,jvm错误等,不建议捕获Error,也无需throws Error及其子类,比如OutOfMemoryError,StackOverflowError
public void stackLeak(){
        length++;
        stackLeak();
    }

    public static void main(String[] args) {
        StackOverTest stackOverTest = new StackOverTest();
        try {
            stackOverTest.stackLeak();
        }catch (Throwable e){
            System.out.println("length : "+ stackOverTest.length);
            e.printStackTrace();
        }
    }
    out: 
    length : 18894
@Test
    public void test(){
        ArrayList list = new ArrayList();
        try {
            while (true){
                list.add(new Object());
            }
        }catch (OutOfMemoryError e){
            e.printStackTrace();
        }
    }

在这里插入图片描述

  • Exception异常,Exception类以及他的子类,代表程序运行时发送的各种不期望发生的事件。可以被Java异常处理机制使用,是异常处理的核心
Checked异常体系
  1. unchecked——所有的RuntimeException 及其子类 统称 Runtime异常,例如ArrayIndexOutOfBoundsException,NullPointerException,这样的异常,也可以不处理。对于这些异常,我们应该修正代码,而不是去通过异常处理器处理
  2. checked——不是runtime异常的则被称为Checked异常,例如SQLException , IOException,ClassNotFoundException,它要求开发者必须来处理这些异常,要么throw,要么try—catch
  • checked异常提现了java的设计 – 没有完善错误处理的代码根本不会被执行。
finally和return的坑
  • finally中的return 会覆盖 try 或者catch中的返回值
  • 不要在finally中抛出异常
  • finally用来释放资源最巴适
 /**
     * return 3
     * 结论:finally中的return 会覆盖 try 或者catch中的返回值
     * 分析:try…catch…finally中的return,他们共同向同一个内存地址写入返回值,后执行的将覆盖先执行的数据
     * */
    public int getNum(int num){
        try{
            int result = 10/num;
            return 1;
        }catch (Exception e){
            System.out.println(e.getMessage());
            return 2;
        }finally {
            return 3;
        }
    }

    /**
     * return 2
     *
     * */
    public int getNum2(int num){
        try{
            int result = 10/num;
            return 1;
        }catch (Exception e){
            System.out.println(e.getMessage());
            return 2;
        }finally {
        }
    }

    /**
     * return 1
     *
     * */
    public int getNum3(int num){
        try{
            int result = 10/num;
            return 1;
        }catch (Exception e){
            System.out.println(e.getMessage());
        }finally {
        }
        return 0;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值