Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this try-catch block valid?

Tags:

c#

try-catch

Newby question...

Is it valid to do:

try
{
    // code which may fail
}
catch
{
    Console.Writeline("Some message");
}

Or do I always have to use:

try
{
    // code which may fail
}
catch (Exception e)
{
    Console.Writeline("Some message");
}
like image 394
PeeHaa Avatar asked Mar 03 '26 10:03

PeeHaa


2 Answers

Both blocks are valid.

The first will not have an exception variable.

If you are not going to do anything with the exception variable but still want to catch specific exceptions, you can also do:

try 
{
   // your code here
}
catch(SpecificException)
{
   // do something - perhaps you know the exception is benign
}

However, for readability I would go with the second option and use the exception variable. One of the worst things to do with exceptions is swallow them silently - at the minimum, log the exception.

like image 163
Oded Avatar answered Mar 04 '26 23:03

Oded


Yep, absolutely, such a catch block called general catch clause, see more interesting details in the C# Language Specification 4.0, 8.10 The try statement:

A catch clause that specifies neither an exception type nor an exception variable name is called a general catch clause. A try statement can only have one general catch clause, and if one is present it must be the last catch clause

like image 42
sll Avatar answered Mar 04 '26 23:03

sll