Search code examples
c#.netwinformsexceptionmvp

A Method which return a value cannot be passed to exception handler


I'm handling exceptions centrally in a method (ExecuteAction(Action action)). I have a problem when passing action to this method when it returns a value.

In following code I'm getting this error:

Since 'System.Action' returns void, a return keyword must not be followed by an object expression

How to solve this problem?

public decimal CalculateInstalment(decimal amount, int months)
{
    this.ExecutAction(() =>
    {
        var result = amount / months;
        return Math.Round(result, 2);
    });
}

protected bool ExecutAction(Action action)
{
    try
    {
        action();
        return true;
    }
    catch (NullReferenceException e) { _MessageService.ShowErrorMessage(e); return false; ; }
    catch (System.Data.SqlTypes.SqlTypeException e) { _MessageService.ShowErrorMessage(e); return false; }
    catch (System.Data.SqlClient.SqlException e) { _MessageService.ShowErrorMessage(e); return false; }
    catch (System.Exception e) { _MessageService.ShowErrorMessage(e); return false; };
}

Solution

  • As others have said, Action types do not return a value, but you can refer to outer variables. If you're trying to get the value, consider a setup like this:

    public decimal CalculateInstalment(decimal amount, int months)
    {
        var result = 0.0;
        this.ExecutAction(() =>
        {
            result = Math.Round((amount / months), 2);
        });
    
        return result;
    }
    
    protected bool ExecutAction(Action action)
    {
        try
        {
            action();
            return true;
        }
        catch (NullReferenceException e) { _MessageService.ShowErrorMessage(e); return false; ; }
        catch (System.Data.SqlTypes.SqlTypeException e) { _MessageService.ShowErrorMessage(e); return false; }
        catch (System.Data.SqlClient.SqlException e) { _MessageService.ShowErrorMessage(e); return false; }
        catch (System.Exception e) { _MessageService.ShowErrorMessage(e); return false; };
    }