Given the following code:
try
// code1
try
// code2
catch ex as exception
end try
// code3
catch ex as exception
end try
Are there any side effects to naming the two exception variables the same or should they have different names?
Given the following code:
try
// code1
try
// code2
catch ex as exception
end try
// code3
catch ex as exception
end try
Are there any side effects to naming the two exception variables the same or should they have different names?
Nope, that should be fine. They're entirely independent variables. At least, that's the case in C# - I couldn't say for certain in VB, but I'd be really surprised if there were any side-effects beyond potential confusion when reading the code :)
In particular, the two variables have different scopes, as neither is really nested within the block declaring the other - the "inner" one is declared within the outer try block. If you wrote a try/catch block within the catch block then that nested catch block couldn't reuse the same variable name.
I cannot answer for VB.
According to the C# specification (§8.10) the exception variable is a local variable whose scope extends over the catch block.
This means that there is no trouble using the same name for this variable in separate catch blocks. This will work just fine:
static void Main(string[] args)
{
try
{
bool success = true;
MyData myData = ReadMyDataFromFile();
try
{
WriteMyDataToDB(myData);
}
catch (SqlException ex)
{
Console.WriteLine("An error occured saving the data.\n" + ex.Message);
success = false;
}
WriteLogFile(myData, success);
}
catch (IOException ex)
{
Console.WriteLine("An error occured reading the data or writing the log file.\n" + ex.Message);
}
}
In this case, the second catch block will catch any IOException that occurs through the process, while the first catch block will catch any SqlException that occurs in WriteMyDataToDB(MyData)
, and the fact that the catch variables have the same name makes no difference.
If you have a try-catch within another catch block (which would be pretty unusual), then you will run into problems reusing the same name.
static void Main(string[] args)
{
try
{
DoStuff();
}
catch (IOException ex)
{
try
{
Console.WriteLine("IOException" + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("Another exception!" + ex.Message);
}
}
}
Will give the following error:
A local variable named 'ex' cannot be declared in this scope because it would give a different meaning to 'ex', which is already used in a 'parent or current' scope to denote something else