@finally ?

Discussion in 'Mac Programming' started by Sydde, Nov 4, 2011.

  1. Sydde macrumors 68020

    Sydde

    Joined:
    Aug 17, 2009
    #1
    I am a little confused as to why one would need the third part of the @try/@catch block. It seems like @finally is just the natural flow that would follow. Is it used for organizing/clarifying the code?
     
  2. chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #2
    An @finally block is executed regardless of how the @try block ends. So if there's a return in the @try, or an exception is thrown or rethrown (caught or not), the @finally is always executed.

    If you only place code after the @try (natural sequential flow), then neither a return in the @try-block nor a rethrown exception (nor other flow-control, such as break) will cause the post-try code to execute.

    I recommend making a test program that returns or breaks from an @try block, in order to illustrate the behavior. Throw an uncaught exception, too. Often, the best way to understand how something works is to make it do something you write.

    Reference doc:
    http://developer.apple.com/library/....html#//apple_ref/doc/uid/TP30001163-CH13-SW1
    A @finally{} block contains code that must be executed whether an exception is thrown or not.
     
  3. Mac_Max macrumors 6502

    Joined:
    Mar 8, 2004
    #3
    Adding to chown33's comments, "finally" is often times used for cleaning up resources you no longer need, closing network connections, closing databases, etc.
     

Share This Page