只是一个简单的问题,我似乎无法在网上找到正确的答案。
当我有一个 try/catch block ,并且我想捕获错误时,我应该使用 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
或者只是为了方法签名?
在这种情况下,我将尝试确保属性文件不为空并且包含值,捕获错误的正确方法是什么?
另外,为了清楚起见,我的目标是尽可能让用户清楚错误是什么,以便他们立即知道他们需要修复其属性文件。
最佳答案
取决于你想做什么。
如果在发生异常时无法履行方法的约定(例如,您无法返回您想要的值),则抛出一个新的异常。 (但请注意,仅仅重新抛出一个新异常没有多大意义。只需将该方法声明为 throws NoSuchELementException
并让异常传播。)
如果您的契约(Contract)在发生异常时可以履行(即,如果没有找到元素,您可以返回null
),那么您应该捕获该异常(使用以下命令记录它) System.err.println
如果你愿意的话),然后继续执行。
关于抛出新异常的第一个选项的旁注:
您应该始终抛出适合当前抽象级别的异常。例如,如果调用 getUserFromList(...)
方法,并且由于某些与集合相关的问题而遇到 NoSuchElementException
,则应该捕获该异常并抛出 >NoSuchUserException
。
突出差异:
try {
currentUser=(String) userList.nextElement();
currentPass=(String) credentials.get(currentUser);
} catch(NoSuchElementException nsee) {
^^^^^^^
System.err.println("Is properties file blank?");
throw new NoSuchUserException("Is properties file blank?");
^^^^
}
关于Java - 简单的异常处理查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9879125/