The try statement:


/*
 :
In JScript, the variable used to hold a caught exception is visible in the enclosing scope. The variable exists after the catch clause has finished executing but ceases to exist after the function where the catch clause was located exits.
*/
function foo() 
{
    try 
    { 
       throw "hello"; 
    } 
    catch(x) 
    { 
         document.write(x); 
    }
      document.write(x); // x should not be visible here } foo();
/*
Output:
    IE: hellohello 
    FF: hello (followed by error „x is not defined‟) 
 Opera: same as FF 
Safari: same as FF
*/

/*
 :
    Catch is defined as creating a new object with the caught object as a property and putting the new object at the head of the scope chain. If the caught object is a function, calling it within the catch supplies the head of the scope chain as the this value. The called function can add properties to this object. This implies that for code of this shape:
    The reference to 'x' within the catch is not necessarily to the local declaration of 'x'; this gives Catch the same performance problems as with. If the call to E above were specified to supply the global object (rather than the head of the scope chain) as the this value, the performance issue evaporates and the catch variable can be treated as a local scoped to the catch clause.
*/
function foo()
{ 
	this.x = 11; 
} 
x = "global.x";
try
{ 
	throw foo;
} 
catch(e)
{
	document.write(x) // Should print "global.x"
	e(); 
	document.write(x) // Should add x to e // (Both IE and Firefox modify the global x)
}
document.write(x);
/*
Output: 
     IE: prints "global.x1111 
     FF: same as IE 
  Opera: prints "global.x11global.x"
 Safari: same as Opera
*/

좋은 웹페이지 즐겨찾기