<p>What are the best practices to consider when catching exceptions and re-throwing them? I want to make sure that the <code>Exception</code> object's <code>InnerException</code> and stack trace are preserved. Is there a difference between the following code blocks in the way they handle this?</p>

<pre><code>try
{
    //some code
}
catch (Exception ex)
{
    throw ex;
}
</code></pre>

<p>Vs:</p>

<pre><code>try
{
    //some code
}
catch
{
    throw;
}
</code></pre>

[{'answer_id': 22628, 'author': 'Darren Kopp', 'author_id': 77, 'author_profile': 'https://Stackoverflow.com/users/77', 'pm_score': 9, 'selected': True, 'text': '<p>The way to preserve the stack trace is through the use of the <code>throw;</code> This is valid as well</p>\n\n<pre><code>try {\n  // something that bombs here\n} catch (Exception ex)\n{\n    throw;\n}\n</code></pre>\n\n<p><code>throw ex;</code> is basically like throwing an exception from that point, so the stack trace would only go to where you are issuing the <code>throw ex;</code> statement.</p>\n\n<p><a href="https://stackoverflow.com/questions/22623/net-throwing-exceptions-best-practices#22649">Mike</a> is also correct, assuming the exception allows you to pass an exception (which is recommended).</p>\n\n<p><a href="http://openmymind.net" rel="noreferrer">Karl Seguin</a> has a <a href="http://codebetter.com/blogs/karlseguin/archive/2008/05/29/foundations-of-programming-pt-8-back-to-basics-exceptions.aspx" rel="noreferrer">great write up on exception handling</a> in his <a href="http://openmymind.net/FoundationsOfProgramming.pdf" rel="noreferrer">foundations of programming e-book</a> as well, which is a great read.</p>\n\n<p>Edit: Working link to <a href="http://openmymind.net/FoundationsOfProgramming.pdf" rel="noreferrer">Foundations of Programming</a> pdf. Just search the text for "exception".</p>\n'}, {'answer_id': 22639, 'author': 'Forgotten Semicolon', 'author_id': 1960, 'author_profile': 'https://Stackoverflow.com/users/1960', 'pm_score': 5, 'selected': False, 'text': "<p>When you <code>throw ex</code>, you're essentially throwing a new exception, and will miss out on the original stack trace information.  <code>throw</code> is the preferred method.</p>\n"}, {'answer_id': 22648, 'author': 'swilliams', 'author_id': 736, 'author_profile': 'https://Stackoverflow.com/users/736', 'pm_score': 4, 'selected': False, 'text': "<p>The rule of thumb is to avoid Catching and Throwing the basic <code>Exception</code> object. This forces you to be a little smarter about exceptions; in other words you should have an explicit catch for a <code>SqlException</code> so that your handling code doesn't do something wrong with a <code>NullReferenceException</code>.</p>\n\n<p>In the real world though, catching <em>and logging</em> the base exception is also a good practice, but don't forget to walk the whole thing to get any <code>InnerExceptions</code> it might have.</p>\n"}, {'answer_id': 22649, 'author': 'Mike', 'author_id': 1573, 'author_profile': 'https://Stackoverflow.com/users/1573', 'pm_score': 7, 'selected': False, 'text': '<p>If you throw a new exception with the initial exception you will preserve the initial stack trace too..</p>\n\n<pre><code>try{\n} \ncatch(Exception ex){\n     throw new MoreDescriptiveException("here is what was happening", ex);\n}\n</code></pre>\n'}, {'answer_id': 22650, 'author': 'Kevin Griffin', 'author_id': 1226, 'author_profile': 'https://Stackoverflow.com/users/1226', 'pm_score': 2, 'selected': False, 'text': '<p>I would definitely use:</p>\n\n<pre><code>try\n{\n    //some code\n}\ncatch\n{\n    //you should totally do something here, but feel free to rethrow\n    //if you need to send the exception up the stack.\n    throw;\n}\n</code></pre>\n\n<p>That will preserve your stack.</p>\n'}, {'answer_id': 22673, 'author': 'Erick B', 'author_id': 1373, 'author_profile': 'https://Stackoverflow.com/users/1373', 'pm_score': 2, 'selected': False, 'text': '<p>You may also use:</p>\n\n<pre><code>try\n{\n// Dangerous code\n}\nfinally\n{\n// clean up, or do nothing\n}\n</code></pre>\n\n<p>And any exceptions thrown will bubble up to the next level that handles them.</p>\n'}, {'answer_id': 3179808, 'author': 'Vinod T. Patil', 'author_id': 200752, 'author_profile': 'https://Stackoverflow.com/users/200752', 'pm_score': 3, 'selected': False, 'text': '<p>You should always use "throw;" to rethrow the exceptions in .NET,</p>\n\n<p>Refer this,\n<a href="http://weblogs.asp.net/bhouse/archive/2004/11/30/272297.aspx" rel="noreferrer">http://weblogs.asp.net/bhouse/archive/2004/11/30/272297.aspx</a></p>\n\n<p>Basically MSIL (CIL) has two instructions - "throw" and "rethrow":</p>\n\n<ul>\n<li>C#\'s "throw ex;" gets compiled into MSIL\'s "throw"  </li>\n<li>C#\'s "throw;" - into MSIL "rethrow"!</li>\n</ul>\n\n<p>Basically I can see the reason why "throw ex" overrides the stack trace.</p>\n'}, {'answer_id': 5653239, 'author': 'redcalx', 'author_id': 15703, 'author_profile': 'https://Stackoverflow.com/users/15703', 'pm_score': 0, 'selected': False, 'text': "<p>FYI I just tested this and the stack trace reported by 'throw;' is not an entirely correct stack trace. Example:</p>\n\n<pre><code>    private void foo()\n    {\n        try\n        {\n            bar(3);\n            bar(2);\n            bar(1);\n            bar(0);\n        }\n        catch(DivideByZeroException)\n        {\n            //log message and rethrow...\n            throw;\n        }\n    }\n\n    private void bar(int b)\n    {\n        int a = 1;\n        int c = a/b;  // Generate divide by zero exception.\n    }\n</code></pre>\n\n<p>The stack trace points to the origin of the exception correctly (reported line number) but the line number reported for foo() is the line of the throw; statement, hence you cannot tell which of the calls to bar() caused the exception.</p>\n"}, {'answer_id': 9186501, 'author': 'notlkk', 'author_id': 576300, 'author_profile': 'https://Stackoverflow.com/users/576300', 'pm_score': 3, 'selected': False, 'text': "<p>A few people actually missed a very important point - 'throw' and 'throw ex' may do the same thing but they don't give you a crucial piece of imformation which is the line where the exception happened.</p>\n\n<p>Consider the following code:</p>\n\n<pre><code>static void Main(string[] args)\n{\n    try\n    {\n        TestMe();\n    }\n    catch (Exception ex)\n    {\n        string ss = ex.ToString();\n    }\n}\n\nstatic void TestMe()\n{\n    try\n    {\n        //here's some code that will generate an exception - line #17\n    }\n    catch (Exception ex)\n    {\n        //throw new ApplicationException(ex.ToString());\n        throw ex; // line# 22\n    }\n}\n</code></pre>\n\n<p>When you do either a 'throw' or 'throw ex' you get the stack trace but the line# is going to be #22 so you can't figure out which line exactly was throwing the exception (unless you have only 1 or few lines of code in the try block). To get the expected line #17 in your exception you'll have to throw a new exception with the original exception stack trace.</p>\n"}, {'answer_id': 11284872, 'author': 'CARLOS LOTH', 'author_id': 139042, 'author_profile': 'https://Stackoverflow.com/users/139042', 'pm_score': 5, 'selected': False, 'text': '<p>Actually, there are some situations which the <code>throw</code> statment will not preserve the StackTrace information. For example, in the code below:</p>\n\n<pre><code>try\n{\n  int i = 0;\n  int j = 12 / i; // Line 47\n  int k = j + 1;\n}\ncatch\n{\n  // do something\n  // ...\n  throw; // Line 54\n}\n</code></pre>\n\n<p>The StackTrace will indicate that line 54 raised the exception, although it was raised at line 47.</p>\n\n<pre><code>Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.\n   at Program.WithThrowIncomplete() in Program.cs:line 54\n   at Program.Main(String[] args) in Program.cs:line 106\n</code></pre>\n\n<p>In situations like the one described above, there are two options to preseve the original StackTrace:</p>\n\n<p><strong>Calling the Exception.InternalPreserveStackTrace</strong></p>\n\n<p>As it is a private method, it has to be invoked by using reflection: </p>\n\n<pre><code>private static void PreserveStackTrace(Exception exception)\n{\n  MethodInfo preserveStackTrace = typeof(Exception).GetMethod("InternalPreserveStackTrace",\n    BindingFlags.Instance | BindingFlags.NonPublic);\n  preserveStackTrace.Invoke(exception, null);\n}\n</code></pre>\n\n<p>I has a disadvantage of relying on a private method to preserve the StackTrace information. It can be changed in future versions of .NET Framework. The code example above and proposed solution below was extracted from <a href="http://weblogs.asp.net/fmarguerie/archive/2008/01/02/rethrowing-exceptions-and-preserving-the-full-call-stack-trace.aspx" rel="noreferrer">Fabrice MARGUERIE weblog</a>.</p>\n\n<p><strong>Calling Exception.SetObjectData</strong></p>\n\n<p>The technique below was suggested by <a href="https://stackoverflow.com/users/77724/anton-tykhyy">Anton Tykhyy</a> as answer to <a href="https://stackoverflow.com/questions/57383/in-c-how-can-i-rethrow-innerexception-without-losing-stack-trace">In C#, how can I rethrow InnerException without losing stack trace</a> question.</p>\n\n<pre><code>static void PreserveStackTrace (Exception e) \n{ \n  var ctx = new StreamingContext  (StreamingContextStates.CrossAppDomain) ; \n  var mgr = new ObjectManager     (null, ctx) ; \n  var si  = new SerializationInfo (e.GetType (), new FormatterConverter ()) ; \n\n  e.GetObjectData    (si, ctx)  ; \n  mgr.RegisterObject (e, 1, si) ; // prepare for SetObjectData \n  mgr.DoFixups       ()         ; // ObjectManager calls SetObjectData \n\n  // voila, e is unmodified save for _remoteStackTraceString \n} \n</code></pre>\n\n<p>Although, it has the advantage of relying in public methods only it also depends on the following exception constructor (which some exceptions developed by 3rd parties do not implement):</p>\n\n<pre><code>protected Exception(\n    SerializationInfo info,\n    StreamingContext context\n)\n</code></pre>\n\n<p>In my situation, I had to choose the first approach, because the exceptions raised by a 3rd-party library I was using didn\'t implement this constructor.</p>\n'}, {'answer_id': 40586475, 'author': 'Mark', 'author_id': 6192931, 'author_profile': 'https://Stackoverflow.com/users/6192931', 'pm_score': 4, 'selected': False, 'text': '<p>Nobody has explained the difference between <code>ExceptionDispatchInfo.Capture( ex ).Throw()</code> and a plain <code>throw</code>, so here it is. However, some people have noticed the problem with <code>throw</code>.</p>\n\n<p>The complete way to rethrow a caught exception is to use <code>ExceptionDispatchInfo.Capture( ex ).Throw()</code> (only available from .Net 4.5).</p>\n\n<p>Below there are the cases necessary to test this:</p>\n\n<p>1.</p>\n\n<pre><code>void CallingMethod()\n{\n    //try\n    {\n        throw new Exception( "TEST" );\n    }\n    //catch\n    {\n    //    throw;\n    }\n}\n</code></pre>\n\n<p>2.</p>\n\n<pre><code>void CallingMethod()\n{\n    try\n    {\n        throw new Exception( "TEST" );\n    }\n    catch( Exception ex )\n    {\n        ExceptionDispatchInfo.Capture( ex ).Throw();\n        throw; // So the compiler doesn\'t complain about methods which don\'t either return or throw.\n    }\n}\n</code></pre>\n\n<p>3.</p>\n\n<pre><code>void CallingMethod()\n{\n    try\n    {\n        throw new Exception( "TEST" );\n    }\n    catch\n    {\n        throw;\n    }\n}\n</code></pre>\n\n<p>4.</p>\n\n<pre><code>void CallingMethod()\n{\n    try\n    {\n        throw new Exception( "TEST" );\n    }\n    catch( Exception ex )\n    {\n        throw new Exception( "RETHROW", ex );\n    }\n}\n</code></pre>\n\n<p>Case 1 and case 2 will give you a stack trace where the source code line number for the <code>CallingMethod</code> method is the line number of the <code>throw new Exception( "TEST" )</code> line.</p>\n\n<p>However, case 3 will give you a stack trace where the source code line number for the <code>CallingMethod</code> method is the line number of the <code>throw</code> call. This means that if the <code>throw new Exception( "TEST" )</code> line is surrounded by other operations, you have no idea at which line number the exception was actually thrown.</p>\n\n<p>Case 4 is similar with case 2 because the line number of the original exception is preserved, but is not a real rethrow because it changes the type of the original exception.</p>\n'}]
['https://Stackoverflow.com/questions/22623', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/357/']