Labels

Tuesday, March 31, 2009

Variable Declaration Or Initialization within Try Block - Myth

Hi,

 

Here the articles covers whether the variables declaration within the try block is correct practice or not.

Reference: http://msdn.microsoft.com/en-us/library/0yd65esw(VS.80).aspx

 

-          Inside a try block, declare only those variables that are not required to be access outside the try i.e. neither in catch nor in finally. See below ‘The name 'dt does not exist in the current’.

-          When inside a try block, only initialize variables that are declared therein; otherwise, an exception can occur before the execution of the block is completed. See below ‘Use of unassigned local variable’.

 

 

 

 

 

 

try

{

    DataTable dt = new DataTable();

}

catch (Exception ex)

{

    // Error - The name 'dt does not exist in the current }

finally

{

    Dt.Dispose() // Error - The name 'dt does not exist in the current

}

 

 

public int Me()

{

    int x;

    try

    {

        // Don't initialize this variable here.

        x = 123;

    }

    catch

    {

    }

 

  return x; // Error: Use of unassigned local variable 'x'.

}

 

 

 

 

 

Regards,

Arun Manglick

1 comment: