java throw new Exception throw e

  public static void main(String[] args) {
    try {
      ttt();
    } catch (Exception e) {
      logger.error("err", e);
    }
  }

  public static void ttt() {
    try {
      ttt2();

    } catch (Exception e) {
      logger.error("err", e);
      throw e;
    }
  }

  public static void ttt2() {
    int count = 1 / 0;
  }

catch後打印e

catch後不打印e

結論?

如果項目代碼裏面有統一異常處理
如spring的 @ControllerAdvice. @ExceptionHandler(BindException.class) 中打印了整個異常堆棧.

我們在方法裏面logger一次e,會導致重複打印,日誌不好看。

所以只需要選其一,如果沒有統一異常處理,還是內部方法都打印e比較好;
如果有,那可以只打印相關錯誤信息,或者直接throw原來的,不要catch了,只打印原ex.又繼續拋出新的

  public static void ttt(String param) {
    try {
      ttt2();

    } catch (Exception e) {
      // catch後
      logger.error("err. param:{}", param);
      throw new RuntimeException("hello err");
    }
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章