variable scope
-
Hi all, A beginners question: I define
SqlCommand myCommand;
in a function I then dotry { myCommand = new SqlCommand(mySelectQuery,mySQLConnection); } catch(System.Exception e) {}
I get an errormessageUse of unasigned local variable myCommand
I see why I get the message but have no real clue on how I can use the try - catch without casting the errormessage. regards Stijn
-
Hi all, A beginners question: I define
SqlCommand myCommand;
in a function I then dotry { myCommand = new SqlCommand(mySelectQuery,mySQLConnection); } catch(System.Exception e) {}
I get an errormessageUse of unasigned local variable myCommand
I see why I get the message but have no real clue on how I can use the try - catch without casting the errormessage. regards Stijn
Some comments: 1. All too often you don't want to try/catch - a program should have way more try/finally than try/catch. If you're accessing myCommand after the catch ((System.Exception e) {}, myCommand may have not been initialized due to an exception, as you're "swallowing" exceptions on the catch. Notice that if you add a "throw;" statement to your catch, the error message goes away. Be aware that "swallowing" exceptions is a bad practice and leads to code that's hard to debug and problems hard to detect, as the problem will never happen near the real error. 2. If this doesn't solve, you can substitute SqlCommand myCommand; for SqlCommand myCommand = null; Again, use this wisely, as you can hide exceptions and introduce subtle bugs... Yes, even I am blogging now!