簡體   English   中英

最后阻止行為不同

[英]Finally block to behave differently

我有這樣的病

String str = null;

try{
  ...
  str = "condition2";
}catch (ApplicationException ae) {
  str = "condition3";
}catch (IllegalStateException ise) {
  str = "condition3";
}catch (Exception e) {
  str = "condition3";
}

if(str == null){
  str = "none";
}

現在我要總結所有str = "condition3"; 在一排。 最終,塊始終運行,因此無法滿足我的需求。 還有什么可以做的。

從Java 7開始,您可以在單個catch塊中捕獲多種異常類型 代碼看起來像這樣:

String str = null;

try {
    ...
    str = "condition2";
} catch (ApplicationException|IllegalStateException|Exception ex) {
    str = "condition3";
}

順便說一句:您發布的代碼以及我的Java 7代碼都可以折疊為catch (Exception e) ,因為ExceptionApplicationExceptionIllegalStateException的超類。

您可以使用Java 7異常處理語法。 Java 7在一個catch塊中支持多種異常處理。 經驗-

String str = null;

try{
  ...
  str = "condition2";
}catch (ApplicationException | IllegalStateException | Exception  ae) {
  str = "condition3";
}
try{
  ...
  str = "condition2";
}catch (Exception ae) {
 str = "condition3";
}

就像其他所有子類一樣,都是Exception的子類。 如果要顯示其他消息,則可以嘗試以下操作

try{
   ...
   str = "condition2";
}catch(ApplicationException | IllegalStateException e){
if(e instanceof ApplicationException)
    //your specfic message
    else if(e instanceof IllegalStateException)
    //your specific message
    else
        //your specific message
    str = "condition3";
}

如果使用的Java 7功能是在單個catch塊中捕獲多個異常,則必須添加“ final”關鍵字

catch (final ApplicationException|IllegalStateException|Exception ex) {

當您在ApplicationExceptionIllegalStateException捕獲塊以及一般異常Exception捕獲塊中執行相同操作時,可以刪除ApplicationExceptionIllegalStateException塊。

我將在這里走出去並提供以下信息:

String str = null;

 try{
     ...
     str = "condition2";
 }catch (Throwable e) {
    str = "condition3";
 }
 finally {
     if(str == null){
         str = "none";
     }
 }

如果這不是“總結”的意思,請澄清。

請閱讀

http://www.tutorialspoint.com/java/java_exceptions.htm http://docs.oracle.com/javase/tutorial/essential/exceptions/

暫無
暫無

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

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