Java中的异常处理

异常介绍

JDK文档描述:

The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement.Similarly, only this class or one of its subclasses can be the argument type in a catch clause. For the purposes of compile-time checking of exceptions, Throwable and any subclass of Throwable that is not also a subclass of either RuntimeException or Error are regarded as checked exceptions.

在JAVA语言中,Throwable 是所有错误和异常的超类;只有Throwable类或其子类的实例才能被Java虚拟机或者throw子句抛出,才能作为作为catch的参数。为了达到编译时检查异常,Throwable类和其之类(不包括Error和RuntimeException)都被视为checkException。

Java中的异常可以是函数中的语句执行时引发的,也可以是程序员通过throw 语句手动抛出的,

异常处理

1)throws: 将方法执行语句中可能出现的异常抛给上级调用者处理,作用在方法上, 后面接异常的类名

3)try{}catch(), 直接在代码中处理异常

2) throw :  程序员自己手动抛出,当我们throw 编译时异常一定要用throws和try-catch处理

在try-catch进行异常处理时,可以选择指定finally子句。以下面的结构为例,来讲解下finally的执行过程。

try{
    statementA;
    return statementB;
} catch(Exception e){
    return statementC;
} finally{
    statementD;
}

当程序正常执行的时候,先执行statementA -> statementB -> statementD -> 返回statementB的值。这里面经常涉及的面试题是statementB是一条语句比如a+b,程序一定是先计算a+b,然后执行statementD,然后再把先前计算好的a+b的值作为结果返回。

当程序有异常发生的时候,比如statementA发生了异常,则执行顺序为statementA -> statementC -> statementD -> 返回statementC的值。

finally块不管异常是否发生,只要对应的try执行了,则它一定也执行。只有一种方法让finally块不执行:System.exit()。因此finally块通常用来做资源释放操作:关闭文件,关闭数据库连接等等。

异常的链化

概念:以一个异常对象为参数构造新的异常对象,然后抛出。新的异对象将包含先前异常的信息。

在模块化开放中,假设B模块调用A模块的方法,如果A模块发生异常,则B也将不能完成而发生异常,但是B在抛出异常时,会将A的异常信息掩盖掉,这将使得异常的根源信息丢失。异常的链化可以将多个模块的异常串联起来,使得异常信息不会丢失。

@RestController
@RequestMapping("/ht/dev/common")
public class CommonController{

    @Autowired
    private CommonService commonService;

    @GetMapping("/get/user")
    public Result<UserInfo> getUser() {
       try{
        UserInfo info = commonService.getUserInfo();
       }catch(Exception e){
         log.error("url:{/ht/dev/common/get/user}, methode:{}", "/ht/dev/common/get/user", "getUser()", e);
       
        } 
        return Result.ofSuccess(info);
    }
}


@Service
public class CommonService{
    public UserInfo getUserInfo(HttpServletRequest request) {
        UserInfo userInfo = new UserInfo();
        String user = Base64Util.decode2(request.getHeader("user"));
        try {
            userInfo = JSONObject.parseObject(user, UserInfo.class);
        } catch (Exception e) {
           throw e; //直接抛给顶层处理
        }
        return userInfo;
    }
}

public class Base64Util {
    private static Logger logger = LoggerFactory.getLogger(Base64Util.class);

    public static String decode2(String str) {
        String result = "";
        if (StringUtil.isNullOrEmpty(str)) {
            return str;
        }
        // 解码
        byte[] base64Data = Base64.getDecoder().decode(str);
        try {
            result = new String(base64Data, "utf-8");
        } catch (Exception e) {
            throw new RuntimeException(e); //链化:以一个异常对象为参数构造新的异常对象。
        }
        return result;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值