【发布时间】:2014-02-15 23:45:14
【问题描述】:
我有一个 FileUtils 类,我想调用它来进行一些验证,如果它是错误的,它需要返回一个很好的错误消息,说明验证失败的原因。所以我有:
public static boolean isValidFile(File file) throws Exception
{
if(something)
throw new Exception("Something is wrong");
if(somethingElse)
throw new Exception("Something else is wrong");
if(whatever)
throw new Exception("Whatever is wrong");
return true;
}
public void anotherMethod()
{
try
{
if(isValidFile(file))
doSomething();
} catch (Exception e) {
displayErrorMessage(e.getMessage());
}
}
但这对我来说似乎很奇怪,因为 isValidFile 调用永远不会是假的。此外,如果我颠倒 if 条件的顺序以快速启动代码,如果它是错误的,它看起来就更奇怪了。另外,我不喜欢将异常处理代码作为传递错误消息的一种方式。
public void anotherMethod()
{
try
{
if(!isValidFile(file))
return;
doSomething();
..
doMoreThings();
} catch (Exception e) {
displayErrorMessage(e.getMessage());
}
}
有没有办法在不使用异常的情况下完成所有这些操作,并且仍然能够让 isValidFile() 方法返回错误的指示,而无需返回带有错误代码的 int,就像在 C 等中看到的那样。
【问题讨论】:
标签: java exception error-code