The finally Block


The finally Block

The finally statement contains statements to execute after the try and catch statements execute, but before the statements following the try and catch statements execute. The finally block executes whether or not an exception is thrown. (Note also that if an exception is thrown, the statements in the finally block execute even if no catch block handles the exception.)

If you're working with some crucial resource that you've locked in your code and an error occurs, for instance, that resource may never be unlocked if the error prevents the full code from running. To make sure that the resource is freed whether or not an error occurred, you can put code to unlock the resource in the finally statement, which executes regardless of whether an exception is thrown. Here's an example:

 lockResource()  try {      useResource()  }  catch(e){      reportResourceError()  }  finally {   unlockResource()   }  


Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net