Why does this compile?

  • Thread starter Thread starter tni
  • Start date Start date
T

tni

int x = 0; int y = 0; int z = 0;

try
{
z = x / y;
}
catch (Exception) // THIS IS NOT A (DECLARATION)!!!!
{

}

Thomas
 
Why shouldn't it compile? If you want to catch exceptions, you don't have
to tell it a specific exception variable to store it in...

-mdb

(e-mail address removed) wrote in @g14g2000cwa.googlegroups.com:
 
int x = 0; int y = 0; int z = 0;

try
{
z = x / y;
}
catch (Exception) // THIS IS NOT A (DECLARATION)!!!!
{

}

C# isn't like Java - you don't have to declare a variable to catch the
exception "into".

From the ECMA spec:

<quote>
When a catch clause specifies a class-type, the type must be
System.Exception or a type that derives from System.Exception.

When a catch clause specifies both a class-type and an identifier, an
exception variable of the given name and type is declared. The
exception variable corresponds to a local variable with a scope that
extends over the catch block. During execution of the catch block, the
exception variable represents the exception currently being handled.
For purposes of definite assignment checking, the exception variable is
considered definitely assigned in its entire scope.

Unless a catch clause includes an exception variable name, it is
impossible to access the exception object in the catch block.
</quote>
 
Hello (e-mail address removed),
int x = 0; int y = 0; int z = 0;

try
{
z = x / y;
}
catch (Exception) // THIS IS NOT A (DECLARATION)!!!!
{
}

If you don't use the exception instance within the catch block, you don't
need to declare an identifier (C# lang spec §8.10). Of course you cannot
access the original exception in this case ;-)

Cheers,
 
int x = 0; int y = 0; int z = 0;

try
{
z = x / y;
}
catch (Exception) // THIS IS NOT A (DECLARATION)!!!!
{

}

Thomas
Because there aren't any errors in it.

rossum
 
int x = 0; int y = 0; int z = 0;

try
{
z = x / y;
}
catch (Exception) // THIS IS NOT A (DECLARATION)!!!!
{

}

For 2 related reasons: Code like the following is common

catch(ExceptionType1)
{
// the only interesting thing about the exception is its type
DoStuff();
}
catch(ExceptionType2)
{
// cleanup stuff here but don't use exeception
throw; // rethrows exception
}


and

catch(Exception ex)
{
}

will give a compiler warning about unused variable ex.

Of course it seems quite reasonable to me that the compiler should not warn
in this particular case but that's how it is.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top