c# - I got an error on 'Exception' part and i don't know why -
when run code got error on catch (exception e) part don't know why , compiler say's "a local variable named 'e' cannot declared in scope because give different meaning 'e', used in 'parent or current' scope denote else"
        try         {              //form query insert company , output generated id              mycommand.commandtext = "insert comp(company_name) output inserted.id values (@company_name)";             mycommand.parameters.addwithvalue("@company_name", txtcompname);             int companyid = convert.toint32(mycommand.executescalar());              //for next scenario, in case need execute command before committing transaction              mytrans.commit();              //output message in message box             messagebox.show("added", "company added 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() +                                       " encountered while attempting roll transaction.");                 }             }              messagebox.show("an exception of type " + e.gettype() +                               "was encountered while inserting data.");             messagebox.show("record written database.");          }                 {             myconnection.close();         } hope reply! thanks!
you have variable named e somewhere else in local scope , there no way disambiguate between two.
most in event handler eventargs parameter named e , should rename 1 of e identifiers else.
the following examples demonstrate issue:
- a conflicting parameter name - void myeventhandler(object source, eventargs e) // ^^^ { try { dosomething(); } catch (exception e) // ^^^ { ohno(e); // "e" this? exception or eventargs?? } }
- a conflicting local variable - void mymethod() { decimal e = 2.71828; // ^^^ try { dosomething(); } catch (exception e) // ^^^ { ohno(e); // "e" this? exception or decimal?? } }
- anonymous function (lambda) - void mymethod() { decimal e = 2.71828; // ^^^ var sum = enumerable.range(1, 10) .sum(e => e * e); //which "e" multiply? // ^^^ }
note following not cause same error, because able disambiguate this keyword:
class myclass {     int e;      void mymethod()     {         try         {             dosomething(e); //here int32 field         }         catch (exception e)         {             ohno(e); //here exception             dosomethingelse(this.e); //here int32 field         }     }  } 
Comments
Post a Comment