我似乎总是走到十字路口,我不知道如何在不重新抛给调用者的情况下处理异常。
有没有更好的方法来处理下面的情况?
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。
最佳答案
这完全取决于。
一方面,您是真的想将 IOException
渗透到上层,还是想将下层可能发生的各种异常封装在特定于应用程序的异常中?
您需要能够从此异常中恢复吗?如果不是,RuntimeException
是否更合适? (即使您确实需要异常可恢复,您是否在提供高级别声明性异常处理的环境中操作?)
使用 NullObject
模式来避免返回 null 是否更有意义?
(等:)
关于java - 如何处理本地化异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7425098/