簡體   English   中英

捕獲DocumentException是個好主意嗎?

[英]Is catching DocumentException a good idea?

我有一個實用程序方法,該方法讀取xml文件並轉換為字符串,如下所示:

public static String readFile(String xmlFileName) throws IOException, DocumentException{
        String xmlMsg = null;
        Resource resource = null;
        InputStream inputStream = null;
        try{
            resource = new ClassPathResource(xmlFileName);
            inputStream = resource.getInputStream();
            SAXReader reader = new SAXReader();
            Document doc = reader.read( inputStream );
            xmlMsg = doc.asXML();
        }finally{
            if(inputStream != null){
                inputStream.close();
            }
        }
        return xmlMsg;
    }

如果我在上面的代碼中捕獲DocumentException並將其重新拋出,是否是個壞主意,如下所示:

public static String readFile(String xmlFileName) throws IOException, DocumentException{
        String xmlMsg = null;
        Resource resource = null;
        InputStream inputStream = null;
        try{
            resource = new ClassPathResource(xmlFileName);
            inputStream = resource.getInputStream();
            SAXReader reader = new SAXReader();
            Document doc = reader.read( inputStream );
            xmlMsg = doc.asXML();
        }catch (DocumentException e){
           throw new DocumentException("some message");
        }finally{
            if(inputStream != null){
                inputStream.close();
            }
        }
        return xmlMsg;
    }

因此,將處理DocumentException的責任留給調用者是一個壞主意嗎?

不可以,讓調用者處理Exception可以使早期拋出較晚

我有一個問題是:

}catch (DocumentException e){
    throw new DocumentException("some message");

為什么要catch (DocumentException e) ,然后拋出一個新實例以剝離所有有用信息 首先,您根本無法抓住它,而讓它滲入可以處理它的人手中。

另外,請使用Java 7 try-with-resources,而不要使用finally 因此,您的代碼應為:

public static String readFile(String xmlFileName) throws IOException, DocumentException {
    try (final InputStream is = new ClassPathResource(xmlFileName).getInputStream()) {
        final SAXReader reader = new SAXReader();
        final Document doc = reader.read(inputStream);
        return doc.asXML();
    }
}

我刪除了聲明為null然后重新分配的變量,我討厭這種做法,許多其他Java開發人員也是如此-擺脫這種習慣。 在需要時聲明它們立即分配 在垃圾回收語言中,最小范圍的原則非常重要。

我還更改了它以直接return而不是出於某種原因存儲值。

    catch (DocumentException e){ // here you are catching exception
       throw new DocumentException("some message");// now you are changing
       // exception message 
    }

這是一個壞習慣,您必須將最初拋出的異常拋出到更高級別,然后才能在那里處理Exception

這樣比較好

   catch (DocumentException e){
       throw new DocumentException("some message",e);
   }

暫無
暫無

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

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