Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between catch(Exception), catch() and just catch

I want to know if I can safely write catch() only to catch all System.Exception types. Or do I've to stick to catch(Exception) to accomplish this. I know for other exception types (e.g. InvalidCastException), I have to specify the type as catch(InvalidCastException). In other words, I'm asking if the following code samples are the same.

This ...

try
{
    //do something
}
catch(Exception)
{
    //handle exception
}

this ...

try
{
    //do something
}
catch() //Causes compile time error "A class type expected"
{
    //handle exception
}

and this ...

try
{
    //do something
}
catch
{
    //handle exception
}

update: There was an error in my question. catch() is not allowed in c#.

like image 300
CleanCoder Avatar asked Jan 17 '12 19:01

CleanCoder


2 Answers

In a perfect world, you shouldn't use catch(Exception) nor catch (alone) at all, because you should never catch the generic Exception exception. You always should catch more specific exceptions (for instance InvalidOperationException...etc.).

In a real world, both catch(Exception) and catch (alone) are equivalent. I recommend using catch(Exception ex) when you plan to reuse the exception variable only, and catch (alone) in other cases. Just a matter of style for the second use case, but if personally find it more simple.

What's really important (even if it's out of the scope of your question) is that you never write the following piece of code:

try
{
}
catch (SpecificException ex)
{
    throw ex;
}

This would reset the stack trace to the point of the throw. In the other hand:

try
{
}
catch (SpecificException)
{
    throw;
}

maintain the original stack trace.

like image 80
ken2k Avatar answered Mar 11 '23 19:03

ken2k


Both constructs (catch () being a syntax error, as sh4nx0r rightfully pointed out) behave the same in C#. The fact that both are allowed is probably something the language inherited from C++ syntax.

Others languages, including C++/CLI, can throw objects that do not derive from System.Exception. In these languages, catch will handle those non-CLS exceptions, but catch (Exception) won't.

like image 36
Frédéric Hamidi Avatar answered Mar 11 '23 19:03

Frédéric Hamidi