Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between the 3 catch block variants in C# ( 'Catch', 'Catch (Exception)', and 'Catch(Exception e)' )?

Tags:

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?

like image 645
jordan Avatar asked Jun 12 '13 19:06

jordan


2 Answers

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.

like image 144
Eric Lippert Avatar answered Sep 22 '22 05:09

Eric Lippert


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

like image 23
DonBoitnott Avatar answered Sep 23 '22 05:09

DonBoitnott