I have a FileUtils class that I would like to call that does some validation, and if it's wrong, it needs to return a good error message as to why the validation failed. So I have:

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

But this just seems odd to me because the isValidFile call can never be false. Also if I reverse the order of the if condition to do a quick boot out of the code if it's false, it's even weirder looking. Plus I don't like having exception handling code as a way of passing an error message.

public void anotherMethod()
{
    try
    {
        if(!isValidFile(file))
            return;
        doSomething();
        ..
        doMoreThings();
    } catch (Exception e) {
        displayErrorMessage(e.getMessage());
    }
}

Is there a way to do all this without using Exceptions to and still be able to have the isValidFile() method return an indication of what the error is without returning an int with an error code like you see in C, etc.

有帮助吗?

解决方案

You can e.g. change your method to

public static List<String> isValidFile(File file)

When the file is valid return an empty list or null,
otherwise return a list with the validation problems. The
return value is your indication if validation failed or not.

其他提示

You could do something like this:

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

Not really pretty, but it gets the job done.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top