mercredi 17 août 2016

Should exceptions be used to unwinding process back to main?

Now this is really quite difficult for me to explain so please bear with me.

I've been wondering as of late the best way to "unwind" every chained method back to a main method when certain circumstances are met. For example, say I make a call to a method from Main and from that method I call another one and so on. At some point I may want to cancel all further operations of every method that is chained and simply return to the Main method. What is the best way to do this?

I'll give a scenario:

In the following code there are 3 methods, however when Method1 calls Method2 with a null value it should unwind all the way back to Main without further operations in Method2 (EG the "Lots of other code" section).

public static void main(String[] args) 
{
    try
    {
        Method1();
    }
    catch( ReturnToMainException e )
    {
        // Handle return \\
    }
}

public static void Method1() throws ReturnToMainException
{
    String someString = null;
    Method2( someString  );

    // Lots more code after here
}

public static boolean Method2( String someString )
{
    if( someString == null )
        throw new ReturnToMainException();
    else if( someString.equals( "Correct" ))
        return true;
    else
        return false;
}

In this example I use a throw which I've read should only be used in "Exceptional Circumstances". I often run into this issue and find myself simply doing If/Else statements to solve the issue, but when dealing with methods that can only return True/False I find I don't have enough options to return to decide on an action. I guess I could use Enumerators or classes but that seems somewhat cumbersome.

Aucun commentaire:

Enregistrer un commentaire