Search code examples
c#asp.net-mvcentity-frameworktry-catchusing

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);
    }

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.