Catch vs Catch (Exception e) and Throw vs Throw e

前端 未结 2 1028
慢半拍i
慢半拍i 2020-12-05 03:06

Are these two code examples the same? Catch and Catch (Exception e) have the same output, and the result is also the same if I write

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 03:38

    If we ignore the "unused variable" warning, the only time there is a practical difference between

    catch {...}
    

    and

    catch(Exception ex) {...}
    

    is when some non-C# code is throwing a non-Exception exception. C++ can throw anything. In .NET 1.1, you had to use catch (no (Exception ex)) to handle these unusual exceptions. However, this was problematic - not least, you can't see what was thrown! So in .NET 2.0 and above this is wrapped by default, so even if C++ throws, say, a string - you see it as an Exception subclass. Note that this can be disabled via a configuration setting, but: don't. Leave it alone!

    The issue of throw; vs throw ex; is already mentioned, and relates to stack-traces. You can use throw in both cases, causing the original stack-trace to be preserved.

提交回复
热议问题