Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interrupting long running method pattern

I am currently using this somewhat tedious pattern to generate error message for user running some long operation:

string _problem;

void SomeLongRunningMethod()
{
    try
    {
        _problem = "Method1 had problem";
        Method1();
        _problem = "Unexpected error during doing something in Method2";
        if(Method2())
        {
            _problem = "Method3 fails";
            Method3();
        }
        _problem = "Not possible to obtain data";
        var somedata = Method4();
    }
    catch(Exception)
    {
        MessageBox.Show("Problem with some long running method: " + _problem);
    }
}

Either of methods may throw and I want to tell the user at which step failure occurs. This is done by setting _problem before running any of them.

In some cases I can use different Exception types to catch, but that doesn't works always, e.g. both Method1 and Method2 can throw InvalidOperationException().

This repeated code looks like a pattern. Though I can't recognize it. Any ideas? How to improve readability?

like image 948
Sinatr Avatar asked May 26 '26 09:05

Sinatr


1 Answers

You could use when in the catch to differentiate between the same exception types and to check which method threw this exception:

void SomeLongRunningMethod()
{
    try
    {
        Method1();
        if (Method2())
        {
            Method3();
        }
        var somedata = Method4();
    }
    catch (InvalidOperationException invEx) when (invEx.TargetSite?.Name == nameof(Method1))
    {
        // ...
    }
    catch (InvalidOperationException invEx) when (invEx.TargetSite?.Name == nameof(Method2))
    {
        // ...
    }
    catch (Exception ex)
    {
        // ...
    }
}
like image 142
Tim Schmelter Avatar answered May 30 '26 07:05

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!