2

Is there any difference between these ways of using/try-catch blocks?

First :

public bool Insert(SomeEntity entity)
{
    bool result = false;
    
    try
    {
        using (var db = new MyEntities())
        {
            db.AddToSomeEntity(entity);
            db.SaveChanges();
            
            result = true;
        }
    }
    catch (Exception e)
    {
        //
    }
    return result;
}

Second :

public bool Insert(SomeEntity entity)
{
    bool result = false;
    using (var db = new MyEntities())
    {
        try
        {
            db.AddToSomeEntity (entity);
            db.SaveChanges();
            result = true;
        }
        catch (Exception e)
        {
                    //
        }
    }
    
    return result;
}

Does it affect performance?

This string was added in order to satisfy SO submit validation rule.

0

1 Answer 1

1

I do not think it violates any rules it the idea at what point you want to send your context to garbage collection i would recommend using the second method since it more concrete and you will send the object to garbage collection when your function was totally executed otherwise you might be getting an exception where you try to use the context while it no longer available

Sign up to request clarification or add additional context in comments.

2 Comments

So, if I want to know any info about exception, I won't find anything in the first case?
you may but second will give you more info

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.