我總是似乎來到了一個十字路口,在那裏我不完全知道如何處理異常,而不會重新投向調用者。如何處理本地異常?
有沒有更好的方法來處理下面的情況?
private DataHandler retrieveFromGridFS(ObjectId id) throws IOException
{
GridFS gridFS = new GridFS(getDBReference());
GridFSDBFile out = gridFS.find(id);
File temp = File.createTempFile(
(String)out.getMetaData().get("productName"),
(String)out.getMetaData().get("productType"));
out.writeTo(temp);
return new DataHandler(new FileDataSource(temp));
}
上面private
方法可以拋出IOException
。
利用這種方法,像這樣:
public DataHandler retrieveProduct(String productId) throws IOException
{
ObjectId id = new ObjectId(productId);
DataHandler handler = null;
try
{
handler = retrieveFromGridFS(id);
}
catch(IOException ex)
{
logger.error(ex);
throw new IOException("A problem occurred retrieving product.");
}
return handler;
}
我被迫重新拋出這樣我就不會冒險返回null。
不要扔掉原來的異常tho,從日誌文件中進行調試要困難得多使用'throw new IOException(「檢索產品時出現問題」,前);' – MeBigFatGuy
+1;絕對 - 刪除潛在的原因是調試的麻煩。 –