将异常作为参数传递给Java方法是否是不良实践?

huangapple go评论64阅读模式
英文:

Is it bad practice to pass exception as argument to a method in java

问题

我有一个方法,如果服务中出现异常,应该回滚。在异常块中,回滚服务在失败时会抛出异常。我为回滚创建了一个服务,但我将异常作为参数传递给第二个方法。这样做是不是不良做法?

public static void method1() {
    try {
       // 做可能引发异常的操作
    } catch (Exception e) {
         method2(data, e);
      }
}

public static void method2(String data, CustomException ce) {
    try {
     // 可能失败的回滚服务
    } catch(Exception e) {
        log.warn("回滚失败!!!");
         ce.addSuppressed(e);
      }
 }
英文:

I have a method that should rollback if an exception occurs in a service. In the exception block, the rollback service throws an exception when it fails. I created a service for rollback but i pass exception as argument to second method. is that bad practice?

public static void method1() {
    try{
       //do something that can throw exception
    } catch (Exception e) {
         method2(data, e);
      }
}

public static void method2(String data, CustomException ce) {
    try{
     // rollback service that could fail
    } catch(Exception e) {
        log.warn("rollback failed!!!");
         ce.addSuppressed(e);
      }
 }

答案1

得分: 0

最终,Exception 是普通的 Java 对象,其特殊之处在于可以被抛出。如果我们拒绝将 Exception 作为参数,将会剥夺例如在 JavaEE 的 ExceptionMapper 中找到的集中处理异常的能力。如果我们拒绝将 Exception 作为参数使用,很可能违反 DRY 原则 和很可能违反 关注点分离原则。这两者都可能导致代码变得更难阅读和维护。

此外,如果我们的某个方法接受 Object(或 Object...Collection<Object> 等)作为参数,我们将无法阻止可能将 Exception 作为参数传递进来。

总之,我认为没有理由认为将 Exception 作为方法参数是不良实践。

英文:

At the end of the day, Exceptions are normal Java objects with the added property that they can be thrown. If we were to deny Exceptions as parameters, it would take away the ability to, for example, have centralized handler-methods for Exceptions (a concept found, for example, in JavaEE's ExceptionMapper). If we were to deny the use of Exceptions as parameters, we would most probably violate the DRY principle and most probably the Separation of Concerns principle. Both of which could lead to harder to read and maintain code.

Furthermore, if one of our method accepts Object (or Object... or Collection&lt;Object&gt;, ...) as parameter, we are not able to prevent that maybe an Exception is passed as parameter.

In conclusion, I see no reason why it should be a bad practice to pass an Exception as method parameter.

huangapple
  • 本文由 发表于 2020年8月19日 06:10:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63477313.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定