我有一个if条件来检查值并抛出新的NumberFormatException
有没有其他方法来编码这个
if (foo)
{
throw new NumberFormatException
}
// ..
catch (NumberFormatException exc)
{
// some msg...
}
我有一个if条件来检查值并抛出新的NumberFormatException
有没有其他方法来编码这个
if (foo)
{
throw new NumberFormatException
}
// ..
catch (NumberFormatException exc)
{
// some msg...
}
如果你正在做这样的事情:
try
{
// some stuff
if (foo)
{
throw new NumberFormatException();
}
}
catch (NumberFormatException exc)
{
do something;
}
那么当然,您可以完全避免异常并在条件块内执行“做某事”部分。
如果您的目标是避免引发新异常:
if(foo)
{
//some msg...
} else
{
//do something else
}
如果您可以以另一种更优雅的方式处理它们,请不要抛出异常。异常是昂贵的,并且应该只用于发生超出您控制的事情的情况(例如,数据库服务器没有响应)。
如果您试图确保一个值的设置和格式正确,您应该尝试以更优雅的方式处理这些条件的失败。例如...
if(myObject.value != null && Checkformat(myObject.Value)
{
// good to go
}
else
{
// not a good place to be. Prompt the user rather than raise an exception?
}
在 Java 中,您可以尝试使用正则表达式解析字符串,然后再尝试将其转换为数字。
如果您试图捕获自己的异常(为什么???),您可以这样做:
try { if (foo) throw new NumberFormatException(); }
catch(NumberFormatexception) {/* ... */}
如果您试图用其他错误处理机制替换抛出异常,您唯一的选择是返回或设置错误代码 - 问题是您必须去确保在其他地方检查它。
例外是最好的。
如果您知道将导致您抛出 NumberFormatException 的流程,请编写处理该情况的代码。您不应该将异常层次结构用作程序流机制。