gpt4 book ai didi

Java - 简单的异常处理查询

转载 作者:行者123 更新时间:2023-12-04 05:52:44 25 4
gpt4 key购买 nike

只是一个快速的问题,我似乎无法在网上找到正确的答案。

当我有一个 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还是仅用于方法签名?
在这种情况下捕获错误的正确方法是什么,我将尝试确保属性文件不是空白并包含值?
此外,为了清楚起见,我的目标是尽可能让用户清楚错误是什么,以便他们立即知道他们需要修复他们的属性文件。

最佳答案

取决于你想做什么。

如果你的方法契约(Contract)无法完成 如果出现异常(例如,您无法返回您打算返回的值),则抛出一个新异常。 (但是请注意,仅仅重新抛出一个新异常并没有多大意义。只需将该方法声明为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com