We’re going to build a wrapper around the traditional Objective-c try-catch and pass in Swift closures to execute as part of the code.


  • Create a new Objective-c class. Pick NSObject as the subclass.
  • Allow Xcode to add a bridging header if you don’t already have one. The bridging header allows Swift code to access Objective-c classes imported through there.
  • Make your TryCatch class visible to the Swift project by importing the Objective-c header.
  • Declare your new try-catch function. We’re using a + to make it a class function for easy use.
+ (void)try:void(^)())try catch:void(^)(NSException*exception))catch finally:void(^)())finally;
  • Implement the function using the default Objective-c try-catch.
  • Call the closures (blocks) inside each matching part of the try-catch. Only call if the closure (block) isn’t nil.
+(void)try:void (^)())try catch:void (^)(NSException *))catch finally:void (^)())finally{    @try {       try ? try() : nil;    }    @catch (NSException *exception) {       catch ? catch(exception) : nil;    }    @finally {       finally ? finally() : nil;    }}


Use anywhere you need a try catch in your Swift project.

 TryCatch.try({ () -> Void in    //try stuff }, catch: { (exception) -> Void in    //catch exceptions }) { () -> Void in    //close resources }

Harlem App Collective is a design focused, mobile development shop based in Harlem, NY. Email:

Swift Programming

The Swift Programming Language

    William Falcon

    Written by

    PhD Student, AI (NYU, Facebook AI research) • Previously Co-Founder @Nextgenvest, Product Manager, iOS Eng • Prior Goldman Sachs, Bonobos, Columbia

    Swift Programming

    The Swift Programming Language

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade