捕获异常并重新抛出异常时需要考虑哪些最佳实践?我想确保保留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) 在我写入数据库的方法中,我处理错误,如下面的代码所示.在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)