[Objective-C] How do I handle and raise custom exceptions in Objective-C?

In Objective-C, you can handle and raise custom exceptions by following these steps:

  1. Define a custom exception class:

    • Create a new Objective-C class that inherits from the NSException class.
    • Add any additional properties or methods that you require for your custom exception.
  2. Implement your custom exception class:

    • Implement the required initWithName:reason:userInfo: initializer method in your custom exception class.
    • Pass the provided arguments to the superclass initializer using super keyword.
     1// MyCustomException.h
     2@interface MyCustomException : NSException
     3
     4// Custom properties and methods
     5
     6@end
     7
     8// MyCustomException.m
     9@implementation MyCustomException
    10
    11- (instancetype)initWithName:(NSExceptionName)aName reason:(nullable NSString *)aReason userInfo:(nullable NSDictionary *)aUserInfo {
    12    self = [super initWithName:aName reason:aReason userInfo:aUserInfo];
    13    if (self) {
    14        // Custom initialization if needed
    15    }
    16    return self;
    17}
    18
    19// Custom properties and methods implementation
    20
    21@end
    
  3. Raise your custom exception:

    • Use the @throw directive inside a @try block to throw an instance of your custom exception.
    • Pass the appropriate arguments to the initWithName:reason:userInfo: method to provide relevant information about the exception.
     1@try {
     2    // Code that may throw the custom exception
     3    if (/* some condition */) {
     4        NSString *reason = @"Custom exception occurred";
     5        NSDictionary *userInfo = @{ /* optional additional information */ };
     6        MyCustomException *customException = [[MyCustomException alloc] initWithName:@"MyCustomException" reason:reason userInfo:userInfo];
     7        @throw customException;
     8    }
     9}
    10@catch (MyCustomException *exception) {
    11    // Handle the custom exception
    12    NSLog(@"Custom exception caught: %@", exception);
    13}
    14@catch (NSException *exception) {
    15    // Handle other exceptions
    16    NSLog(@"Exception caught: %@", exception);
    17}
    18@finally {
    19    // Cleanup code
    20}
    

Note: It is considered good practice to only use exceptions for exceptional cases, such as programming errors, and not for normal control flow.