java异常处理的一些思考

java异常处理的一些思考

public class ExceptionTest {
    public static void main(String[] args) throws Exception {
        for (int i=0;i<5;i++){
            System.out.println(i);
            if ((i==3)){
                catchMethod();
            }
        }
    }

    static void exceptionMethod() throws Exception{
        System.out.println("exceptionMethod");
        int i = 5/0;
    }

    static void catchMethod2(){
        try {
            int i = 5/0;
        }catch (Exception e){
            System.out.println(e);
        }
    }

    static void catchMethod() throws Exception {
        try {
            int i = 5/0;
        }catch (Exception e){
            System.out.println("catch");
            System.out.println(e);
        }
        System.out.println("after catch");
    }
}

在这里插入图片描述
对于异常,如果在方法内部使用try catch捕捉异常,是不会影响主流程的执行

    public static void main(String[] args) throws Exception {
        for (int i=0;i<5;i++){
            System.out.println(i);
            if ((i==3)){
                exceptionMethod();
            }
        }
    }

对于上面的main方法,执行的结果为
在这里插入图片描述
如果是在方法上抛出异常,是会中断主流程的运行

这里的主流程可能是简单的main方法,也可以是一个复杂的业务流程,对于复杂的业务流程来说最好在流程内部使用try catch捕捉异常,避免中断主流程的运行
对于提供给外部的接口,在方法上使用throws 关键字抛出异常,方便调用方捕捉后觉得是中断流程还是抛出给调用方的上一级
对于调用外部接口的方法,使用try catch捕捉接口可能返回的异常 再决定是抛出还是捕捉异常

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值