netwer
netwer

Reputation: 737

How can I execute all methods if I get exception in the first method?

I have 2 methods: method1() and method2(). Each method can create exception (WebException). I have methodMain() in this method I execute the first method is method1() and them I execute method2(). For example:

public void methodMain()
{
    ...
    try
    {
        method1();
        method2();
    }
    catch (WebException e)
    {
        //do something
    }
    ...
}

If I get exception from method1() the method2() doesn't executed.

How can I execute all methods if I get exception in the first method?

I came up with solution:

public void methodMain()
{
    ...
    try
    {
        method1();
    }
    catch (WebException e)
    {
        //do something
    }
    ...
    try
    {
        method2();
    }
    catch (WebException e)
    {
        //do something
    }
    ...
}

I think my solution is not good and not beautiful.

Again my question: How can I execute all methods if I get exception in the first method?

Upvotes: 0

Views: 86

Answers (2)

pyrocumulus
pyrocumulus

Reputation: 9290

You have two options; either you separate the calls to method1 and method2 in separate try-catch blocks or you move the try-catch to the inside of both methods.

Which option is best depends on what does methods do and where they are called. If you only want to handle/swallow exceptions in this methodMain-method then this is the right solution. However if you want to ignore the exceptions everywhere, then I suggest you move the try-catch blocks to the inside of both methods.

Upvotes: 1

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

Wrap those methods in a delegate and execute it. You can add any number of methods to the actions array and execute in a loop.

public void methodMain()
{
    Action[] actions = new Action[]
    {
       method1,
       method2
    };

    foreach(var method in actions)
    {
        try
        {
            method();
        }
        catch (WebException e)
        {
            //do something
        }
    }
}

Upvotes: 2

Related Questions