【发布时间】:2015-08-31 08:47:59
【问题描述】:
我想在这里破解一下。我正在尝试的是在抛出异常后执行一些业务逻辑。业务逻辑在 catch 块中定义。我不想将 throw 语句保留在 catch 块的末尾。有什么我可以尝试的黑客吗?我在想的是在那个点和里面创建一个抛出异常的线程。我不确定它是否会起作用。请帮帮我。
package demo1.web;
import demo.exceptions.SupportInfoException;
public class TestInnerException {
void testIt() throws Exception{
try{
int i=0;
int j=1/i;
}catch(Exception e){
System.out.println("business logic .. .. . . ");
throw e;
// I want to excute these below line ,
but it is unreachable because you aleready throwing the excetion ..
//any Hacks for it ?
System.out.println("Lines after throwing the exception ... .");
}
System.out.println("I want this logic to be run . . . . .");
}
public static void main(String[] args) throws SupportInfoException, Exception {
TestInnerException t = new TestInnerException();
t.testIt();
}
void testRunTimeEx(){
int i=0;
int j=1/i;
}
}
让我告诉你我的情况,我有 @ExceptionHandler 注释来处理本文中描述的所有异常。 https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc#user-content-sample-application 一些复杂的场景,无法准确解释原因。我在这里想要的是,如果它由 catch 块处理,那么我希望在 @ExceptionHandler 中触发它,因为我还有一些其他业务逻辑。问题是除非抛出异常,否则不会触发@ExceptionHandler。如果它进入 catch 块,我希望它被触发。但是如果 catch 块没有抛出任何异常,它就不会被触发。
在这种情况下,业务逻辑是指一些日志功能。
【问题讨论】:
-
我只是不明白为什么有人会想要这样做?如果你想执行这些行,那么不要在那里抛出异常
-
您不应在异常处理程序/catch/finally 块中进行任何业务登录。关于资源清理
-
重新思考您的设计。
An exception is thrown when a fundamental assumption of the current code block is found to be false。看看this。抛出异常后,您应该无法继续。 -
@MohammadGhazanfar 没错。看起来像是设计的味道。
标签: java