Termonator145 Termonator145 - 3 months ago 10
C# Question

Stop execution of all methods from child method

I am working with a few methods that are called from within other methods, but need to stop processing both methods if an event occurs in the one called from the parent. An example of what I am doing in code would be this:

private void parentMethod()
{
//Do work here
childMethod();
//Do more work here
}
private void childMethod()
{
//Do work (not child labor)

using (var form = new choice(myList))
{
var result = form.ShowDialog();
if (result == DialogResult.OK)
{
int val = form.listIndex;//values preserved after close
//Do something here with these values
string server = myList2[val - 1];
MyList.Clear();
MyList.Add(server);
}
else
{
Exception e = new Exception("Dialog force closed.",null);
throw e;
}
}


So as you can see here, I tried creating an exception to throw; however, because there are number of other methods getting called from the parent method which also can throw exceptions, but can allow the rest of the code to execute, and the parent method in this example is being called from another method that needs to be stopped as well, how do you stop the execution of multiple methods from within a child method, other that doing
Application.Close()
?

Answer

You need to be more specific in your exception catching. In general, a bare catch is bad practice anywhere except the very top level, as is catch (Exception e) or similar. You should determine which exceptions a method can throw, and then only catch those. Other exceptions will then be passed back up the call stack.

For instance, if you have a method A() that might throw an InvalidOperationException, B() that might throw an ArgumentOutOfRangeException or ArgumentNullException, and C() that might throw an AccessViolationException, your code should look like

public int Main()
{
    try
    {
        try
        {
            A()
        }
        catch(InvalidOperationException e)
        {
            //handle
        }

        try
        {
            B()
        }
        catch(ArgumentOutOfRangeException e)
        {
            //handle
        }
        catch(ArgumentNullException e)
        {
            //handle
        }

        try
        {
            C()
        }
        catch(AccessViolationException e)
        {
            //handle
        }
    }
    catch (Exception e)
    {
        //handle all other exceptions
    }
}

Now, if any method out of A,B, and C throws an exception you're not expecting, it will be handled by the final catch block.

If you really must have an exception that can only be handled at the top level, it might be a good idea to create your own Exception class:

 class MyApplicationException : Exception { }

Then, as long as you never use catch (Exception) anywhere other than at the top level, you will be fine.