2014-01-24 24 views
1

我有一个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等

回答

2

您可以例如改变你的方法

public static List<String> isValidFile(File file)

当该文件是有效的返回一个空列表或null
与验证问题,否则返回一个列表。如果验证失败或失败,则表示返回值为

0

你可以做这样的事情:

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); 
    } 
} 

不是真的很漂亮,但它能够完成任务。