测试返回null值

时间:2012-03-27 16:30:52

标签: java android

在我的应用中,我正在解析XML文件 -

        Document doc = XMLfunctions.XMLfromString(xml);

使用以下功能

public final static Document XMLfromString(String xml){

    Document doc = null;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(xml));
        doc = db.parse(is); 

    } catch (ParserConfigurationException e) {
        System.out.println("XML parse error: " + e.getMessage());
        return null;
    } catch (SAXException e) {
        System.out.println("Wrong XML file structure: " + e.getMessage());
         return null;
    } catch (IOException e) {
        System.out.println("I/O exeption: " + e.getMessage());
        return null;
    }

    return doc;
}

如果一切正常,程序会检查结果数量。当我遇到格式错误的xml文件时,我的问题就出现了。例如当一个WordPress文件里面有标签时。发生的事情是我的应用程序崩溃,当我查看日志时程序已捕获异常

   } catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
         return null;

哪个好。现在我要做的是测试null然后调用finish()返回菜单,而不是面对强制关闭。

我用过

if (null==doc){
    Toast.makeText(this, "Sorry The XML File " + target +" is Misformed", Toast.LENGTH_SHORT).show();
       finish();
   }

if (doc==null){
        Toast.makeText(this, "Sorry The XML File " + target +" is Misformed", Toast.LENGTH_SHORT).show();
           finish();
        }

无济于事。处理这些类型情况的最佳方法是什么?

还在搜索 我试过这个

if(XMLfunctions.XMLfromString(xml)==null){
    Toast.makeText(this, "Badly Formed File", Toast.LENGTH_LONG).show();  
    finish();

}

同样的问题 - 调用后的代码行是

int numResults = XMLfunctions.numResults(doc);

功能代码本身是

public static int numResults(Document doc){
        int res = -1;
        Node results = doc.getDocumentElement();
        try{
        res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
        }catch(Exception e){
            res = -1;
        }
        return res;
    }

返回的初始异常消息是正在为函数getXML返回的消息

  

03-27 12:46:26.917:I / System.out(10311):错误的XML文件结构:名称预期>(位置:START_TAG @ 29:27 in java.io.StringReader@405a3d30)

此时它开始抛出致命异常

2 个答案:

答案 0 :(得分:0)

如果您将上面发布的代码包含在函数中,您可以在if循环中调用整个函数,即

if(parseDoc(xml)== null){     Toast.makeText(这是“抱歉XML文件”+目标+“错误”,Toast.LENGTH_SHORT).show(); }

如果您的应用正确捕获异常,则不应强行关闭,除非您的应用中的某些内容试图访问doc并获得空指针。在这种情况下,异常的日志会很有用。

答案 1 :(得分:0)

我建议向上抛出异常并让调用者处理它们。捕获异常并返回null有点不干净。