Question

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);
    }
Was it helpful?

Solution

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.

OTHER TIPS

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.

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

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(
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top