java 中 try-catch,throw和throws的使用

这里不说语法,说下目前遇到的几种使用方法

1.try-catch用来捕获代码段的异常并做出处理,可以放在for循环中防止某次代码出错导致整个for循环断掉

 
  1. for (int i = 0; i < lists.size(); i++) {

  2. try {} catch (Exception e) {

  3. log.error("FOR循环中异常", e);

  4.  
  5. }

  6.  
  7. }

2.try-catch一般用在最上层的程序里,如下可以配合throws和throw再将异常抛给用户,这种情况会使上层代码中断。也可以不选择抛出,如上打印到日志中,这种上层代码会继续运行。

 
  1. public static PlanResult getReturnJson( ) throws Exception{

  2. log.info("getReturnJson : START");

  3. PlanResult resultBean = new PlanResult();

    扫描二维码关注公众号,回复: 3487038 查看本文章
  4. try {} catch (Exception e) {

  5. log.error("获取实体数据异常\r\n", e);

  6. throw e;

  7. } finally {

  8. log.info("getReturnJson : END");

  9. }

  10. return resultBean;

  11. }

3.被调用的方法如果有异常的可能可以通过throws抛给上层处理,不加try catcch的情况如下会自动往上抛,加了try catch需要如上通过throw抛给上层程序

 
  1. public static String setCacheMap(String userId) throws Exception {

  2.  
  3.  
  4. }

  5.  

--------------------- 本文来自 愿望许过很多 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/qq_37654153/article/details/81669858?utm_source=copy

猜你喜欢

转载自blog.csdn.net/chang_ge/article/details/82895424
今日推荐