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#.
In a perfect world, you shouldn’t use
catch(Exception)norcatch(alone) at all, because you should never catch the genericExceptionexception. You always should catch more specific exceptions (for instanceInvalidOperationException…etc.).In a real world, both
catch(Exception)andcatch(alone) are equivalent. I recommend usingcatch(Exception ex)when you plan to reuse the exception variable only, andcatch(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:
This would reset the stack trace to the point of the throw. In the other hand:
maintain the original stack trace.