相关疑难解决方法(0)

捕获和重新抛出.NET异常的最佳实践

捕获异常并重新抛出异常时需要考虑哪些最佳实践?我想确保保留Exception对象InnerException和堆栈跟踪.以下代码块在处理此方式时是否存在差异?

try
{
    //some code
}
catch (Exception ex)
{
    throw ex;
}
Run Code Online (Sandbox Code Playgroud)

VS:

try
{
    //some code
}
catch
{
    throw;
}
Run Code Online (Sandbox Code Playgroud)

.net c# exception-handling rethrow

279
推荐指数
8
解决办法
18万
查看次数

以相同的方法抛出并捕获异常

在我写入数据库的方法中,我处理错误,如下面的代码所示.在catch (DbUpdateException ex)我想重新抛出异常并在最后捕获它catch (Exception ex).

这可能吗,怎么做?下面的代码不会这样做.

        using (Entities context = new Entities())
        {
            try
            {
                context.Office.Add(office);
                retVal = context.SaveChanges();
            }
            catch (DbUpdateException ex)
            {
                SqlException innerException = ex.GetBaseException() as SqlException;
                if (innerException != null && innerException.Number == (int)SQLErrorCode.DUPLICATE_UNIQUE_CONSTRAINT)
                {
                    throw
                        new Exception("Error ocurred");
                }
                //This is momenty where exception is thrown.
                else
                {
                    throw ex;
                }
            }
            catch (Exception ex)
            {
                throw
                    new Exception("Error");
            }
        }
Run Code Online (Sandbox Code Playgroud)

.net c# asp.net-mvc entity-framework

1
推荐指数
1
解决办法
1986
查看次数