Rodrigo Rodrigo - 3 months ago 10
Objective-C Question

In a @try-@catch-@finally block, is it good use finally or to continue normally?

This is a simple Objective-C question.

When you use a

@try
the work flow can run in 2 ways


  • If some NSException appear, the code immediately jump to
    @catch
    block and than to
    @finally

  • If not, finish to run the
    @try
    block and than run
    @finally



So, what is the difference to use or not use the
@finally
block? If I use only:

-(void)function{
@try {
...
}
@catch (NSException *exception) {
...
}
>>>The workflow will run this line in any case?
}


Than the rest of the function will run, or only the
@catch
block if a NSException is created?

Answer

"A @finally block contains code that must be executed whether an exception is thrown or not." Does code in finally get run after a return in Objective-C?

The finally block exists to release/clean up resources like open sockets, open files, database locks, semaphore locks, and so on.

If an error occurs inside of the catch block or the catch block rethrows the exception, then the line:

>>>The workflow will run this line in any case?

is not executed. However, the code in the finally block should be executed. The finally block is the last, best chance to exit cleanly from an application that is about to crash. Even if the application is not about to crash, it is still the best place to cleanup resources because the code inside the finally block is more likely to be executed under unexpected conditions than code outside of the finally block.