Anders Jensen
Anders Jensen

Reputation: 329

How do i express Try/Catch in a control flow graph?

I'm trying to calculate some Cyclomatic Complexity, hence trying to draw a Control Flow Graph. Firstly i'm trying to make it for a fairly simple method.

Firstly i tried drawing it for just the try part like this: Flow Graph

Heres the method:

    [HttpPost]
    public ActionResult GraphMethod([FromForm]string str)
    {
        try
        {
            int affectedRows = this._copyManager.CreateCopy(str);
            if (affectedRows < 1) return BadRequest("Error!");

            return Ok();
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }

How would i extend it to include the entire method, and the try part?

This is my first ever Control Flow Graph, so if i messed it up i would also like to know.

Upvotes: 2

Views: 4915

Answers (2)

MindSwipe
MindSwipe

Reputation: 7910

I would create a TryCreateCopy method and do something very similar to @saya imad's answer
Something like this:

[HttpPost]
public ActionResult GraphMethod([FromForm]string str)
{ 
    // These two if statements can be concatenated into one, 
    // but that would be a bit hard to read
    if (this._copyManager.TryCreateCopy(str, out var affectedRows))
        if (affectedRows > 1)
            return Ok();

    return BadRequest("Error!");
}

// _copyManager Method, there's probably a better way for you
public bool TryCreateCopy(string str, out int affectedRows)
{
    try
    {
        affectedRows = CreateCopy(str);
    }
    // Please also don't do `catch (Exception)`, 
    // if you know which exception gets thrown always catch that
    catch (Exception e)
    {
        affectedRows = -1;
        return false;
    }

    return true;
}

Where the TryCreateCopy method returns true when a copy was created without an exception being thrown, false if one has been thrown* and an out variable with the number of affected rows


* There is probably a better way of doing this than what I showed you (e.g validate method?) as try/ catch is quite resource intensive

Upvotes: 1

sayah imad
sayah imad

Reputation: 1553

For my part i recommande you to use this code , more is simple , more is efficient

[HttpPost]
public ActionResult GraphMethod([FromForm]string str)
{       
        if (this._copyManager.CreateCopy(str) < 1) 
            return BadRequest("Error!");

        return Ok();      
}

Upvotes: 1

Related Questions