Last active
January 30, 2025 07:18
-
-
Save maxkagamine/6980604bd10c8f3b96fa33c66d0f4ca9 to your computer and use it in GitHub Desktop.
ExceptionDispatchInfo.Capture(ex.InnerException).Throw() — Example showing how the stack trace changes versus simply rethrowing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.ExceptionServices; | |
class Program | |
{ | |
static void A() | |
{ | |
try | |
{ | |
B(); | |
// if uncaught: | |
// System.Exception: Oh noes | |
// ---> System.NotImplementedException: The method or operation is not implemented. | |
// at Program.C() | |
// at Program.B() | |
// --- End of inner exception stack trace --- | |
// at Program.B() | |
// at Program.A() | |
// at Program.Main() | |
} | |
catch (Exception ex) | |
{ | |
throw ex.InnerException; | |
// System.NotImplementedException: The method or operation is not implemented. | |
// at Program.A() | |
// at Program.Main() | |
ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); | |
// System.NotImplementedException: The method or operation is not implemented. | |
// at Program.C() | |
// at Program.B() | |
// --- End of stack trace from previous location --- | |
// at Program.A() | |
// at Program.Main() | |
} | |
} | |
static void B() | |
{ | |
try | |
{ | |
C(); | |
} | |
catch (Exception ex) | |
{ | |
throw new Exception("Oh noes", ex); | |
} | |
} | |
static void C() | |
{ | |
throw new NotImplementedException(); | |
} | |
static void Main() | |
{ | |
A(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://sharplab.io/#v2:C4LgTgrgdgPgAgJgIwFgBQcAMACOSB0AStMAJYC2ApvgKIAeAxpQA5kD2UAypWAG6lMAzgG506RLiQB2dAG902RZIBsuACzYAggAoAlAqXy0Sk9mBgAngdPYjNmwCE9o4/YC+10wwCGwBgAtsbXomVlIObEo6fVcbO3sTAHpEs38wNgB3SLp8AEkoKB4QlnYoFwSTYrCOABFSQWZfAPyAMzZ8AGFvVggwSm0ovIKixhLwqF18ABU0zOdPEw9Y7CXPPFU4DScYk3ibcytl3YX7DvmjpSWEnz9A4NHqqGyd+z2K4Fmswqyq0u0AIgA8oEoGxKIJ/gAaZ7ldyeVbLdbqbBnF6KN6mD7pL6ULIAOTYwFy5GYABtKFQoMBKAATX7jZxKeGeNZIDYaACy3lIUD0ngxSh0ulhiiWbiAA===