In C#, what is the difference Between 'Catch', 'Catch (Exception)', and 'Catch(Exception e)' ?
The MSDN article on try-catch uses 2 of them in its examples, but doesn't explain the difference in usage purposes.
try {} catch {} try {} catch (Exception) {} try {} catch(Exception e) {}
How do these differ? Which ones catch all exceptions, and which ones catch specific exceptions?
No one has yet mentioned the historical aspect of this question.
In .NET it is legal to throw an object that does not derive from Exception
. (It is not legal in C#, but it is in some other managed languages.) Many people are unaware of this fact, but it is legal. Since that is crazy, in .NET 2.0 the default was changed: if you attempt to throw something that is not an exception then it is automatically wrapped in the RuntimeWrappedException
class which obviously is an exception. That object is then thrown.
Because of this oddity, in C# 1.0 it was common to see code that did both:
try { do something } catch(Exception) { handle the exception } catch { handle the thrown non-exception }
And in fact there were security and correctness issues; there are situations in which for security reasons you must catch anything that is thrown (possibly to re-throw it) and people would think reasonably that catch(Exception)
caught everything, but it didn't.
Fortunately since .NET 2.0 things have been more sensible; you can rely on catch {}
, catch(Exception) {}
and catch(Exception ex) {}
to all catch everything should you need to.
And finally: if for some crazy reason you want to turn on the C# 1.0 behavior, you can put
[assembly:System.Runtime.CompilerServices.RuntimeCompatibility(WrapNonExceptionThrows = false)]
in your program.
In short...
Catch
without a parameter will receive any exception but provide no means to address it.
Catch (Exception)
will essentially do the same thing, because you've specified the root Exception
type. As opposed to Catch (IOException)
which would only catch the IOException
type.
Catch (Exception ex)
catches all exceptions and provides a means to address it via the ex
variable.
Read more: http://msdn.microsoft.com/en-us/library/ms173160.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With