allencoded
allencoded

Reputation: 7275

How to throw errors properly in C# with using() or try catch?

So I have some code and I am curious how it is best to catch the errors. Should I make a query wrapped in a using which is then wrapped in a try catch? I am thinking the below is that correct?

    try
    {
        using (db)
        {
            string salt = BCryptHelper.GenerateSalt(6);
            var hashedPassword = BCryptHelper.HashPassword(user.Password, salt);

            User newUser = new User
            {
                EmailAddress = user.EmailAddress,
                PasswordSalt = salt,
                PasswordHash = hashedPassword,
                CreatedOn = DateTime.UtcNow
            };

            db.Users.Add(newUser);
            db.SaveChanges();
        }

        return true;
    }
    catch (SqlException exp)
    {
        throw new InvalidOperationException("Steam Id could not be added", exp);
    }

Upvotes: 1

Views: 940

Answers (4)

trevorwong77
trevorwong77

Reputation: 11

The try catch can not catch exception happen within the using block. This cause the system to crash with unhandled exception.

Below is much guarantee from crashes. I am not sure this is due to Entity Framework. Which is quite weird to me.

using (var entities = new AttritionRateEntities())
{
   try
   {
      var ent = entities.AttritionRatePerSetups.FirstOrDefault(

Upvotes: -2

Vinay Pandey
Vinay Pandey

Reputation: 8913

there is a lot, throw new Exception , throw ex, throw they all have their own significance, have a look at this for more detail.

Upvotes: 0

Jason Roell
Jason Roell

Reputation: 6809

Wrapping it in a try, catch and possibly a finally to clean up anything that may need cleaning up is the right way to do it.

Wrapping it in a using will not implement any exception handling but will just dispose of the field that you have contained in the using that implements IDisposable after you leave the scope of the using statement.

Upvotes: 2

theMayer
theMayer

Reputation: 16167

The try...catch (and optional finally) are always guaranteed by the runtime to be used; this is particularly important with finally statements (documentation). The same is also true for a using block (reference).

I would, however, restructure your code such that non-database specific operations are handled outside the try/catch - that way you won't open up a connection to the database only to have something else fail before you need it.

Upvotes: 1

Related Questions