2013-08-30 51 views
2

代碼(Java)的片斷異常處理和日誌記錄:更好的做法

..... 
..... 
if (response.check() == checkNumber) 
{ 
     String message = "You are looking at Wrong Place"; 
     logger.log(message); 
     throw new UserAtWrongPlaceException(message); 
     /* stops here */ 
} 
..... 
... 
if (response.check() == somethingElse) 
{ 
...... 
} 

我有代碼來檢查響應,如果響應等於定義constatnt checkNumber,我想記錄的消息,並拋出異常,但通過這樣做我的代碼執行將在此時停止,而不是繼續進行。

什麼是更好的方式來記錄我的消息,拋出UserAtWrongPlaceException並繼續執行 其餘的代碼?

回答

2

扔在Java的異常總是停止該法的執行。它會返回到任何稱爲該方法的代碼,但例外情況。如果該代碼捕獲到異常,則它會轉到catch塊,否則它會向上拋出異常。

也許你正在尋找一種方法來將異常附加到你的日誌?記錄器有一個方法爲:

logger.log(Level.INFO,message,new UserAtWrongPlaceException(message)); 

當然,你可以拋出一個隨機的異常,但如果你想方法繼續,你必須抓住它:

try { 
    if(response.check() == checkNumber) { 
     String message = "You are looking at Wrong Place"; 
     logger.log(message); 
     throw new UserAtWrongPlaceException(message); 
    } 
} catch(UserAtWrongPlaceException e) { 
    //Do something with the exception, or just ignore it. 
} 

但隨後當然,你也可以不拋出異常,因爲結果將是相同的,並且實例化異常只會降低它的速度。

也許您正在尋找一種方法來繼續該方法,但在結束時拋出異常而不是成功返回。對於這樣的做法,我會在稍後存儲這個例外(儘管承認相當複雜)。像這樣:

UserAtWrongPlaceException exception = null; 
if(response.check() == checkNumber) { 
    String message = "You are looking at Wrong Place"; 
    logger.log(message); 
    exception = new UserAtWrongPlaceException(message); 
} 
... 
if(response.check() == somethingElse) { ... } 
... 
if(exception != null) { 
    throw exception; 
} 
return true; 

但是,如果您選擇該模式,則必須查看如果多個這樣的ifs拋出異常會發生什麼情況。在上面的代碼片段中,這將導致所有異常被記錄,但只有最後被拋出。

請記住,一個方法可以返回,或拋出一個異常。它不能做到這一點,也不能拋出多個例外。

1

如果你想打印出堆棧跟蹤,但不停止,你可以使用執行:

new UserAtWrongPlaceException(message).printStackTrace();