【问题标题】:How do i throw an exception and also execute the remaining business logic in the catch block?我如何抛出异常并在 catch 块中执行剩余的业务逻辑?
【发布时间】: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


【解决方案1】:

这不是黑客,也许没有多大意义。

1) 如果您想throw 一些异常,请立即throw

2) 如果你想在exceptionraise 上做一些业务逻辑,那么做,然后throw exception

但是如果你想抛出并做一些事情,这里没有任何脏代码是不太可能的。对我来说,这似乎是一种代码味道。

question Edit 之后编辑:

虽然是记录,但还是可以在扔之前记录,扔之后再生成日志是没有意义的。

【讨论】:

    猜你喜欢
    • 2019-12-25
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 2011-03-18
    相关资源
    最近更新 更多