Why does a Try/Catch block create new variable scope?

trevor-e picture trevor-e · Jul 25, 2012 · Viewed 42.3k times · Source

For example:

try
{
    SomeObject someObject = new SomeObject();
    someObject.dangerousMethod();
}
catch(Exception e)
{
}
someObject.anotherMethod(); //can't access someObject!

But you can declare it before the try/catch block and then it works fine:

SomeObject someObject;
try
{
    someObject = new SomeObject();
    someObject.dangerousMethod();
}
catch(Exception e)
{
}
someObject.anotherMethod(); //works fine

I'm just wondering the design reason for this. Why are Objects created within the try/catch block not in scope with the rest of the method? Maybe I'm not understanding deep down how a try/catch works besides just watching for Exceptions thrown.

Answer

T.J. Crowder picture T.J. Crowder · Jul 25, 2012

Why are Objects created within the try/catch block not in scope with the rest of the method?

They are. Variables declared