Search code examples
javaexceptionthrow

Java - Simple exception handling query


Just a quick question that I can't seem to find a proper answer to online.

When I have a try/catch block, and I want to catch an error, should I use System.err.println(...) or should I use throw new Exception(...).

For example:

if (null==userList || null==credentials)
    System.err.println("Did you call login() first?");
else
{
    try
    {
        currentUser=(String) userList.nextElement();
        currentPass=(String) credentials.get(currentUser);          
    }
    catch(NoSuchElementException nsee)
    {
        System.err.println("Is properties file blank?");
        //Or should this be
        throw new NoSuchElementException("Is properties file blank?");
        nsee.printStackTrace();
    }
}

EDIT: So is throw not meant to go inside the catch? Can I use throw instead of catch or is it just for method signatures?? What is the correct method of catching an error in this case, where I'll be trying to ensure the properties file is not blank and contains values? Also, for clarity, my goal is to make it as clear as possible to the user what the error is, so they know straight away that they need to fix their properties file.


Solution

  • Depends on what you want to do.

    If the contract of your method can't be fulfilled in case of an exception (i.e. you can't return the value you intended to for instance) throw a new exception. (Note however that just rethrowing a new exception doesn't make much sense. Just declare the method as throws NoSuchELementException and let the exception propagate.)

    If your contract can be fulfilled in case of an exception (i.e. you could return null if no element is found) then you should catch the exception (log it using System.err.println if you like) and then continue execution.


    A side-note on the first option of throwing a new exception:

    You should always throw an exception which is appropriate for the current level of abstraction. If for instance the method is called getUserFromList(...) and you encounter a NoSuchElementException due to some collection-related problem, you should catch the exception and throw a NoSuchUserException.

    To highlight the difference:

    try {
        currentUser=(String) userList.nextElement();
        currentPass=(String) credentials.get(currentUser);          
    
    } catch(NoSuchElementException nsee) {
                  ^^^^^^^
    
        System.err.println("Is properties file blank?");
        throw new NoSuchUserException("Is properties file blank?");
                        ^^^^
    }