我有一个FileUtils类,我想调用它做一些验证,如果它是错误的,它需要返回一个很好的错误信息,为什么验证失败。所以我有:Java - 如何设置验证不同的错误消息
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等