If I have a variable in a try catch block the variable is only in scope within that try block...how can I then refer to this variable from the next try catch block?

Ensure that the variable is defined outside of the try first and assign it a default value.

hmm problem is the variable is TextReader "myvariable" = new StreamReader(); , this is wrapped in the first try block...then how would you refer to myvariable in the next try block as it is out of scope?

Pls do as follwoing:

TextReader myVariable;

  myVariable = new StreamReader();
  //rest of the code

Now since the var is declared outside the try block its available for the next try cblock as you required.


Try-block is the segment for you code to execute safely. This is in-order to eliminate program crush if exception occurs at runtime. The Catch-block is segment to execute in case exception thrown by the runtime environment.

Every mature code must have a catch segment to trap the unexpected exception thrown. Through this segment, programmer can mitigate the program from crushing and do error-handling to provide reliable solution. Do not forget the finally-segment. This segment is executed on both occasions, on exception and on normal execution. It is good to start practicing this segment.

private static Object DoSomethingFunction()
            // Declare the return object here.
            // But don't intialize it. You may not know
            // what lies in the constructor.
            Object p_result;
                // Perform the intialization here.
                p_result = new Object();

                // On runtime error, exeception will be thrown.
            catch(Exception exp)
                // Set result and other resources to null or
                // error handling state.
                p_result = null;
                // Do common resource clean-up before 
                // leaving the function. Usually good practice
                // to release resource before exinting.
            return p_result;

It is necessary to start each module with Try-Catch.