C# catch(DataException) - no variable defined
Asked Answered
D

3

6
static void Main(string[] args)
{
    try
    {
        Console.WriteLine("No Error");
    }
    catch (DataException) /*why no compilation error in this line?*/
    {
        Console.WriteLine("Error....");
    }
    Console.ReadKey();
}

The code is compiling without any error. I do not understand why the first line of the catch block is not giving any compilation error -

catch (DataException)

DataException parameter of the catch block is a class, and it should have a variable next to it such as -

catch (DataException d)

Can someone explain the above behavior?

Dibrin answered 15/9, 2015 at 1:58 Comment(2)
This is valid syntax for when you only care which type of exception occurred, but don't need a stack-trace, etc.Maximilianus
In case you do not need the dBiagio
M
6

In section 8.10 of the C# 5.0 spec, you'll find the syntax definition for try/catch (apologies for the formatting):

catch-clauses:
    specific-catch-clauses       general-catch-clauseopt
    specific-catch-clausesopt   general-catch-clause
specific-catch-clauses:
    specific-catch-clause
    specific-catch-clauses    specific-catch-clause
specific-catch-clause:
    catch    (    class-type    identifieropt    )    block
general-catch-clause:
    catch    block

So you can see that catch { }, catch (Exception) { } and catch (Exception ex) { } are all valid according to the specification.

If you don't specify the optional identifier in the catch block, then you're not able to access any exception details - but sometimes you don't need to, so it's good to not declare a variable you don't intend to access.

Maximilianus answered 15/9, 2015 at 2:14 Comment(0)
A
2

Because catch is not a method. you don't need a parameter beside type. without parameter and just with type, exception of that particular type will be handled with that catch block but the details are ignored.

catch (DataException) allows you to know the type of exception, but you cannot get the details.

for example, i have written a custom exception and overridden Message to format my message. with catch (ExceptionType), you cannot access message.with catch (ExceptionType d), you can access with d.Message

Agbogla answered 15/9, 2015 at 2:7 Comment(0)
Z
2

The way you have currently written it means that you are telling the compiler that when an Exception of type DataException will be thrown, this catch block needs to be processed. And with the way you have written it, you will not have any variable that has the exception stored for you to access later.

Typically a single line of code (not even a block of lines) can throw multiple types of Exception. You want different processing for each kind of Exception.

Zrike answered 15/9, 2015 at 2:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.