Reputation: 71
When i run this code i got an error on the catch (exception e) part i don't know why and the compiler say's "A local variable named 'e' cannot be declared in this scope because it would give a different meaning to 'e', which is already used in a 'parent or current' scope to denote something else"
try
{
//Form Query which will insert Company and will output generated id
myCommand.CommandText = "Insert into Comp(company_name) Output Inserted.ID VALUES (@company_name)";
myCommand.Parameters.AddWithValue("@company_name", txtCompName);
int companyId = Convert.ToInt32(myCommand.ExecuteScalar());
//For the next scenario, in case you need to execute another command do it before committing the transaction
myTrans.Commit();
//Output Message in message box
MessageBox.Show("Added", "Company Added with id" + companyId, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception e)
{
try
{
myTrans.Rollback();
}
catch (SqlException ex)
{
if (myTrans.Connection != null)
{
MessageBox.Show("An exception of type " + ex.GetType() +
" was encountered while attempting to roll back the transaction.");
}
}
MessageBox.Show("An exception of type " + e.GetType() +
"was encountered while inserting the data.");
MessageBox.Show("Record was written to database.");
}
finally
{
myConnection.Close();
}
hope for your reply! Thanks!
Upvotes: 1
Views: 1626
Reputation: 116528
You have a variable named e
somewhere else in the local scope and there would be no way to disambiguate between the two.
Most likely you are in an event handler with the EventArgs
parameter named e
and you should rename one of the e
identifiers to something else.
The following examples demonstrate this issue:
A conflicting parameter name
void MyEventHandler(object source, EventArgs e)
// ^^^
{
try
{
DoSomething();
}
catch (Exception e)
// ^^^
{
OhNo(e);
// Which "e" is this? Is it the Exception or the EventArgs??
}
}
A conflicting local variable
void MyMethod()
{
decimal e = 2.71828;
// ^^^
try
{
DoSomething();
}
catch (Exception e)
// ^^^
{
OhNo(e);
// Which "e" is this? Is it the Exception or the Decimal??
}
}
Anonymous function (lambda)
void MyMethod()
{
decimal e = 2.71828;
// ^^^
var sum = Enumerable.Range(1, 10)
.Sum(e => e * e); //Which "e" to multiply?
// ^^^
}
Note the following does not cause the same error, because you are able to disambiguate with the this
keyword:
class MyClass
{
int e;
void MyMethod()
{
try
{
DoSomething(e); //Here it is the Int32 field
}
catch (Exception e)
{
OhNo(e); //Here it is the exception
DoSomethingElse(this.e); //Here it is the Int32 field
}
}
}
Upvotes: 6
Reputation: 3526
This means earlier you have declared a variable named e, and now in the same block of code, or a block inside of it (this try/catch block) you are again declaring it. Change Exception e to Exception except
and it might work.
Upvotes: 0