Incorrect stacktrace by rethrow

前端 未结 12 1388
不知归路
不知归路 2020-11-29 01:49

I rethrow an exception with \"throw;\", but the stacktrace is incorrect:

static void Main(string[] args) {
    try {
        try {
            throw new Exce         


        
12条回答
  •  Happy的楠姐
    2020-11-29 02:33

    How can I preserve the REAL stacktrace?

    You throw a new exception, and include the original exception as the inner exception.

    but that's Ugly... Longer... Makes you choice the rigth exception to throw....

    You are wrong about the ugly but right about the other two points. The rule of thumb is: don't catch unless you are going to do something with it, like wrap it, modify it, swallow it, or log it. If you decide to catch and then throw again, make sure you are doing something with it, otherwise just let it bubble up.

    You may also be tempted to put a catch simply so you can breakpoint within the catch, but the Visual Studio debugger has enough options to make that practice unnecessary, try using first chance exceptions or conditional breakpoints instead.

提交回复
热议问题