【发布时间】:2012-03-26 20:15:26
【问题描述】:
只是一个简单的问题,我似乎无法在网上找到正确的答案。
当我有一个 try/catch 块并且我想捕获一个错误时,我应该使用 System.err.println(...) 还是应该使用 throw new Exception(...)。
例如:
if (null==userList || null==credentials)
System.err.println("Did you call login() first?");
else
{
try
{
currentUser=(String) userList.nextElement();
currentPass=(String) credentials.get(currentUser);
}
catch(NoSuchElementException nsee)
{
System.err.println("Is properties file blank?");
//Or should this be
throw new NoSuchElementException("Is properties file blank?");
nsee.printStackTrace();
}
}
编辑:那么throw 不是要进入catch 吗?我可以使用throw 而不是catch 还是仅用于方法签名?
在这种情况下捕获错误的正确方法是什么,我将尝试确保属性文件不是空白并且包含值?
另外,为了清楚起见,我的目标是让用户尽可能清楚错误是什么,以便他们立即知道他们需要修复他们的属性文件。
【问题讨论】:
-
我认为它们是不同的问题 - System.err 主要用于调试
-
一个奇怪的问题。重新抛出的决定似乎与您是否要记录它或要记录它的位置无关。