2011-11-18 59 views
1

我有這種方法。 問題是,當這個條件滿足即使在調用catch塊時也正在執行代碼

if (bagList==null||bagList.size()<1 && UngarList==null||UngarList.size()<1) 

它進入catch塊這裏

catch (Exception e) { 

     this.errorText = e.getMessage().toString(); 
     info.setErrorText(this.errorText.toString()); 
     response.setinfo(info); 

    } 

但它畢竟是execuing下一行是

final boolean toProceedorNot = validate(bagList.toArray(new Bag[bagList.size()])) 

什麼如果這是符合要求

if (bagList==null||bagList.size()<1 && UngarList==null||UngarList.size()<1) 
**then directly return the response;** 

這是我的方法

public Response getData(Request request) { 

    Info info = new Info(); 

    Response response = new Response(); 
    String xmlrequest = request.getxmlMessage(); 

    HashMap listMap = new HashMap(); 
    List<Ungar> UngarList = new ArrayList<Ungar>(); 
    List<Bag> bagList = new ArrayList<Bag>(); 

    UniverseStaxParser xmlparser = new UniverseStaxParser(); 
    try { 
     listMap = (HashMap) xmlparser.parseData(xmlrequest); 

     UngarList = (List<Ungar>) listMap.get("UngarItems"); 

     bagList = (List<Bag>) listMap.get("bagItems"); 


     if (bagList==null||bagList.size()<1 && UngarList==null||UngarList.size()<1) 
      throw new Exception("No Valid Data is passed as Input "); 

    } catch (Exception e) { 

     this.errorText = e.getMessage().toString(); 
     info.setErrorText(this.errorText.toString()); 
     response.setinfo(info); 

    } 

    final boolean toProceedorNot = validate(bagList.toArray(new Bag[bagList.size()])); 


    try { 
     if (!toProceedorNot) { 
      info.setErrorText(errorText); 
      response.setinfo(info); 

     } else { 

      // some logic here goes 
     } 
    } catch (Exception e) { 
     errorText = e.getMessage().toString(); 
     info.setErrorText(errorText); 
     response.setinfo(info); 
    } 



    return response; 
} 

回答

6

爲什麼不是執行這些線路?它們不在try/catch之外,沒有任何東西阻止正常的程序執行流程。

除非您從方法返回(或以其他方式更改控制流),否則將繼續執行catch塊後面的語句。

如果要返回catch塊的響應,請從catch塊中返回Response。然而,我不相信這是一個通用的Exception的大用途。

1

我認爲你應該重新設計你的軟件的這一部分:

if (bagList==null||bagList.size()<1 && UngarList==null||UngarList.size()<1) 

如果bagListnull,調用它的方法會拋出異常。如果UngarListnull,調用它的方法將拋出異常。這真的沒有必要。

有這些是否是null不確定性 - 幾行上面,你將它們分配新的價值觀和近立即覆蓋參考,失去參照新創建的對象。這似乎也不錯。

找出哪些條件真的非常特殊,以及您可能會發生哪些條件 - 並嘗試處理與簡單事情不同的例外情況。

+0

調用一個空對象的方法會拋出空指針異常。這是一個常見的錯誤。 – Jasonw

+0

非常感謝大家,我修改了代碼,將它保存在一個try塊中,現在它的工作。 – Revathi

相關問題