try-catch使用反思(-)

在实现okhttp监控功能的时候, 我是用的addInterceptor方式, 代码大概是这样的:

 public class MyIntercept implements Interceptor{

      public Response intercept(Interceptor.Chain chain) throw IOException{

           Response ret = null;  

          try{

                    //代码

                     ret = chain.proceed(chain.request);

                    //代码

              }catch (Exception e){

                 }

            return ret;

      }

}

这么写本意是不能抛出任何异常, 防止用户代码崩溃, 可是后来用户没有网络的时候还是出现了空指针异常。

经过排查和思考,发现我这里try-catch处理了用户的代码, chain.proceed()这个是可能产生异常的,但是窝处理了,所以ret = null 返回给调用者了, 发现问题后我将ret = chain.proceed()放到try-catch外面来,问题成功解决。

     总之,try-catch只处理自己的代码, 用户或者系统的代码不要管, 如果抛异常,让用户或者系统处理。

原文地址:https://www.cnblogs.com/zhangyan-2015/p/5784625.html