C# FAQ: How keep a local variable in scope across a try-catch block

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:FAQs
edit

How keep a local variable in scope across a try-catch block?

Here is the problem:

try
{
   Connection conx = new Connection();
   conx.Open();
}
catch
{  // fails because conx is out of scope
   if (conx != null)
   {
      conx.Close();
   }
}

The preceding code will not work; because, if the Open fails, then the conx variable goes out of scope before the catch block is entered.

Fortunately, there is a simple fix—just declare the variable before entering the try block.

Connection conx = null;  // declare outside the try block
try
{
 
   conx = new Connection();
   conx.Open();
 
}
catch
{
   if (conx != null)
   {
      conx.Close();
   }
}

For examples of this type, the Connection class could be wrapped in a class which implements the IDisposable interface. In this way, instead of extending the scope of the local variable, a using statement could be used.



Personal tools