Java-如何使用不同的错误消息设置验证
我有一个FileUtils类,我想调用它来执行一些验证,如果它是错误的,它需要返回一个好的错误消息,说明验证失败的原因。因此,我:Java-如何使用不同的错误消息设置验证,java,exception,error-code,Java,Exception,Error Code,我有一个FileUtils类,我想调用它来执行一些验证,如果它是错误的,它需要返回一个好的错误消息,说明验证失败的原因。因此,我: public static boolean isValidFile(File file) throws Exception { if(something) throw new Exception("Something is wrong"); if(somethingElse) throw new Exception("
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条件的顺序,在它为false的情况下快速引导代码,它看起来更奇怪。另外,我不喜欢用异常处理代码来传递错误消息
public void anotherMethod()
{
try
{
if(!isValidFile(file))
return;
doSomething();
..
doMoreThings();
} catch (Exception e) {
displayErrorMessage(e.getMessage());
}
}
是否有一种方法可以在不使用异常的情况下执行所有这些操作,并且仍然能够让isValidFile()方法返回错误指示,而不返回带有错误代码的int,如C中所示,等等。您可以将方法更改为
公共静态列表有效文件(文件)
当文件有效时,返回空列表或null
,否则,返回带有验证问题的列表。
返回值是验证是否失败的指示。
您可以执行以下操作:
public static String validateFile(File file)
{
String ret = null;
if(something) {
ret = "Something is wrong";
} else if(somethingElse) {
ret = "Something else is wrong";
} else if(whatever) {
ret ="Whatever is wrong";
}
return ret;
}
public void anotherMethod()
{
String errorMessage = validateFile(file);
boolean fileIsValid = errorMessage == null;
if (fileIsValid) {
doSomething();
} else {
displayErrorMessage(errorMessage);
}
}
不是很漂亮,但它完成了任务