2011-11-18 58 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

相关问题