英文:
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, Exception
s are normal Java objects with the added property that they can be thrown. If we were to deny Exception
s as parameters, it would take away the ability to, for example, have centralized handler-methods for Exception
s (a concept found, for example, in JavaEE's ExceptionMapper
). If we were to deny the use of Exception
s 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<Object>
, ...) 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论