Best practices for catching and re-throwing .NET exceptions

前端 未结 11 1492
野的像风
野的像风 2020-11-22 07:15

What are the best practices to consider when catching exceptions and re-throwing them? I want to make sure that the Exception object\'s InnerException

11条回答
  •  臣服心动
    2020-11-22 08:03

    The way to preserve the stack trace is through the use of the throw; This is valid as well

    try {
      // something that bombs here
    } catch (Exception ex)
    {
        throw;
    }
    

    throw ex; is basically like throwing an exception from that point, so the stack trace would only go to where you are issuing the throw ex; statement.

    Mike is also correct, assuming the exception allows you to pass an exception (which is recommended).

    Karl Seguin has a great write up on exception handling in his foundations of programming e-book as well, which is a great read.

    Edit: Working link to Foundations of Programming pdf. Just search the text for "exception".

提交回复
热议问题