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.
They are. Variables declared within the
try/catchblock are not in scope in the containing block, for the same reason that all other variable declarations are local to the scope in which they occur: That’s how the specification defines it. 🙂 (More below, including a reply to your comment.)Here’s an object created within a
try/catchwhich is accessible outside of it:Note the difference. Where the variable is declared defines the scope in which it exists, not where the object was created.
But based on the method names and such above, the more useful structure for that would be:
Re your comment:
In Java, all blocks create scope. The body of an
if, the body of anelse, of awhile, etc. — they all create a new, nested variable scope:(In fact, even a block without any control structure creates one.)
And if you think about it, it makes sense: Some blocks are conditional, like the one defining the body of an
iforwhile. In the aboveif,barmay or may not have been declared (depending on the value offoo), which makes no sense because of course the compiler has no concept of the runtime value offoo. So probably for consistency, the designers of Java went with having all blocks create a new nested scope. (The designer of JavaScript went the other way — there is no block scope at all, yet, though it’s being added — and that approach also confuses people.)