簡體   English   中英

如何引發異常並在catch塊中執行剩余的業務邏輯?

[英]How do i throw an exception and also execute the remaining business logic in the catch block?

我要在這里亂砍。 我正在嘗試的是在引發異常后執行一些業務邏輯。 業務邏輯在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塊未引發任何異常,則不會觸發它。

在這種情況下,我的業務邏輯是指某些日志功能。

這不是黑客,也許沒有多大意義。

1)如果要throw一些異常,請立即throw

2)如果要在引發exception執行一些業務邏輯,請執行該操作,然后throw exception

但是,如果您要拋出並執行一些操作,那么在這里沒有任何臟代碼的情況下是不可能的。 對我來說似乎有代碼味。

問題編輯后進行編輯

盡管正在記錄日志,但是仍然可以在拋出日志之前進行記錄,但是在拋出日志之后生成日志是沒有意義的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM