Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. variable scope

variable scope

Scheduled Pinned Locked Moved C#
question
2 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    Stijn Goris
    wrote on last edited by
    #1

    Hi all, A beginners question: I define SqlCommand myCommand; in a function I then do try { myCommand = new SqlCommand(mySelectQuery,mySQLConnection); } catch(System.Exception e) {} I get an errormessage

    Use 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

    D 1 Reply Last reply
    0
    • S Stijn Goris

      Hi all, A beginners question: I define SqlCommand myCommand; in a function I then do try { myCommand = new SqlCommand(mySelectQuery,mySQLConnection); } catch(System.Exception e) {} I get an errormessage

      Use 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

      D Offline
      D Offline
      Daniel Turini
      wrote on last edited by
      #2

      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!

      1 Reply Last reply
      0
      Reply
      • Reply as topic
      Log in to reply
      • Oldest to Newest
      • Newest to Oldest
      • Most Votes


      • Login

      • Don't have an account? Register

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • World
      • Users
      • Groups