java异常的捕获及处理 兼论throws与throw

本文详细介绍了Java中的异常处理机制,包括try...catch...finally语句的使用,以及throws和throw关键字的区别。通过两个示例代码对比展示了如何在方法中声明异常、捕获异常并向上抛出异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java异常的捕获及处理 兼论throws与throw

java异常处理可以使用try…catch语句进行处理,也可以使用try…catch…fianlly进行处理。在try语句中捕获异常,在catch语句中处理异常,finally做为异常的统一出口,不管是否发生了异常都要执行此段代码。
throws用在方法申明处,表示本方法不处理异常,有异常向上抛,交给被调用处处理;throw在方法中由用户手工抛出一个异常的实例化对象。
下面比较两段代码和执行结果可以看出异常处理的过程和throws及throw的用法。
第一段代码:

package cn.mldn.demo;

class MyMath{
    public int div(int x, int y) throws Exception{
        System.out.println("-------计算开始----------");
        int result = 0;
        try {   //捕捉异常
            result = x/y;
        } catch (Exception e) { //处理异常
            e.printStackTrace();
            System.out.println("--------处理异常1----------");
//          throw e;    //手工抛出异常
        }finally{
            System.out.println("--------计算结束----------");
        }
        return result;
    }
}

public class TestDemo{
    public static void main(String args[]){
        try {
            System.out.println("运算结果:" + new MyMath().div(10, 0));
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("--------处理异常2----------");
        }
    }
}

代码执行结果如下:
代码1执行结果
可以看到,在public int div(int x, int y) throws Exception方法中由try…catch…finally处理了异常后尽管方法有throws Exception也不会抛出异常给main。

第二段代码:

package cn.mldn.demo;

class MyMath{
    public int div(int x, int y) throws Exception{
        System.out.println("-------计算开始----------");
        int result = 0;
        try {   //捕捉异常
            result = x/y;
        } catch (Exception e) { //处理异常
            e.printStackTrace();
            System.out.println("--------处理异常1----------");
            throw e;    //手工抛出异常
        }finally{
            System.out.println("--------计算结束----------");
        }
        return result;
    }
}

public class TestDemo{
    public static void main(String args[]){
        try {
            System.out.println("运算结果:" + new MyMath().div(10, 0));
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("--------处理异常2----------");
        }
    }
}

代码执行结果如下:
 代码2执行结果
可以看到,在public int div(int x, int y) throws Exception方法中由try…catch…finally处理了异常时,由于

            throw e;    //手工抛出异常

手工抛出了异常,由throws继续向上抛出该异常,交给被调用处main处理,所以main中捕获到了该异常,执行了

catch (Exception e) {
            e.printStackTrace();
            System.out.println("--------处理异常2----------");
        }

这段代码。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值