blog

Home / DeveloperSection / Blogs / Mechanisms for Handling Exception in Objective-C

Mechanisms for Handling Exception in Objective-C

Tarun Kumar2408 26-Oct-2015

Whenever we create any program or application it may be chances to occurring errors or exceptions at runtime and our application stops working or hanging problem with application, at that moment when we face that type of problems it looks ugly according to the user, So dealing these types of exceptional conditions Foundation Framework of Objective-C provides exception handling mechanisms for our program/application. As a result, our code can be much cleaner, easier to write correctly and also easier to maintain.   

Exception handling is based on four compiler directives:


  • @try : Here we define a block of code that can potentially throw an exception, it is also called exception handling domain.
  • @catch() : Here we define a block of code that is thrown after the exception caught by @try block. The parameter of @catch is the exception object thrown locally, this is usually an NSException object, but can be other types of objects, such as NSString objects.
  • @finally : Here we define a block of code that is subsequently executed whether an exception is thrown or not.
  • @throw : This directive is used to throw the exception objects. We throw an exception by instantiating an NSException object and then doing one of two things with it: 

    Using it as the argument of a @throw compiler directive Sending it a raise message

 Following example shows how we throw an exception using the @throw directive: 

 NSException *myObj = [NSException exceptionWithName:@”File Not Found Exception”

 Reason:@”FileNotFound on System”
  userInfo:nil];
     @throw myObj;
    // [myObj  raise];  /* equivalent to above directive */

 

 


Updated 13-Mar-2018

Leave Comment

Comments

Liked By