【问题标题】:Refactoring common code from exception section从异常部分重构公共代码
【发布时间】:2014-11-19 17:01:35
【问题描述】:

我有以下代码重复代码,所以我做错了,必须有更好的方法来做到这一点。我在 catch 部分有一组通用的语句。我不能把它放在 finally 块中,因为这些仅用于异常情况。除了制作单独的方法来保存此代码之外,我还能采取其他方法吗?

public MyResponseDto doSomeWork(MyRequestDto) {
  ....
  String jsonStr = null;
  try {
    jsonStr = new ObjectMapper().writeValueAsString(MyRequestDto);
  } catch (JsonGenerationException e) {
    log.error(e.getMessage());
    myResponseDto .setWorkDone(false);
    myResponseDto .setErrorMessage(e.getMessage());
    return myResponseDto ;
  } catch (JsonMappingException e) {
    log.error(e.getMessage());
    myResponseDto .setWorkDone(false);
    myResponseDto .setErrorMessage(e.getMessage());
    return myResponseDto ;
  } catch (IOException e) {
    log.error(e.getMessage());
    myResponseDto .setWorkDone(false);
    myResponseDto .setErrorMessage(e.getMessage());
    return myResponseDto ;
  }

  myResponseDto = postWorkRequest(jsonStr);
  return myResponseDto ;

}

【问题讨论】:

  • 多异常捕获?无论如何,制作方法有什么问题?

标签: java refactoring


【解决方案1】:
public MyResponseDto doSomeWork(MyRequestDto) {
  ....
  String jsonStr = null;
  try {
    jsonStr = new ObjectMapper().writeValueAsString(MyRequestDto);
  } catch (JsonGenerationException | JsonMappingException e) {
    log.error(e.getMessage());
    myResponseDto .setWorkDone(false);
    myResponseDto .setErrorMessage(e.getMessage());
    return myResponseDto ;
  } 
  myResponseDto = postWorkRequest(jsonStr);
  return myResponseDto ;
}

这就是您在一个catch 中捕获多个异常的方法。其他的可以试试,希望对你有帮助。当然,您可以一次捕获超过 2 个异常!

编辑:请注意,这仅适用于 Java 7 或更新版本

【讨论】:

  • 我相信 OP 不会要求
  • 不确定你的意思.. multicatch 功能是从 java 7 开始的。在回答中提到这一点会很清楚。
  • 我编辑了答案。我知道它很有用,但另一方面,当有人建议使用泛型时,他们通常不会提到它仅适用于 Java 5 或更高版本,对吧? :)
  • 一般情况下一个catch中的异常不能在同一个继承树中,所以你不能。 IOException 必须在单独的 catch 中,并且必须在另外两个 catch 之后,否则会出现编译器错误
  • 是的,会的
【解决方案2】:

如果您使用的是 Java 7,则可以使用 try-multi catch。 https://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-29
    • 1970-01-01
    • 2011-02-26
    • 2013-04-14
    • 1970-01-01
    • 2012-04-04
    相关资源
    最近更新 更多