@finally ?

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

  1. Sydde macrumors 68020


    Aug 17, 2009
    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

    Aug 9, 2009
    Sailing beyond the sunset
    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:
    A @finally{} block contains code that must be executed whether an exception is thrown or not.
  3. Mac_Max macrumors 6502

    Mar 8, 2004
    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