1

I have subclassed NSException class to create CustomException class.

Whenever I catch an exception in code (in @catch), i want to initialize an object of CustomException (subclass of NSException) with the object of NSException that is passed as a parameter to @catch.

Something like this

@catch (NSException * e) {

CustomException * ex1=[[CustomException alloc]initWithException:e errorCode:@"-11011" severity:1];
}

I tried doing it by passing the NSException object to the init method of CustomException. (i replaced the [super init] with the passed NSException object as given below)

//initializer for CustomException
-(id) initWithException:(id)originalException errorCode: (NSString *)errorCode severity:(NSInteger)errorSeverity{

    //self = [super initWithName: name reason:@"" userInfo:nil];
    self=originalException;
    self.code=errorCode;
    self.severity=errorSeverity;

    return self;
}

This doen't work! How can I achieve this?

Thanks in advance

2 Answers2

0
self = originalException;

When you do that you are just assigning a NSException object to your NSCustomException so the following things will happen:

  • You might get a warning when doing the assignment since CustomException is expected but you are passing just a NSException object ;(

  • After that, the compiler will think that self is a CustomException object so it won't complain when calling some methods of CustomException class but it will crash when reaching those.

You should enable initWithName:reason:userinfo: and don't do the assignment.

nacho4d
  • 43,720
  • 45
  • 157
  • 240
0

You are trying to do something which generally[*] isn't supported in any OO language - convert an instance of a class into an instance of one of its subclasses.

Your assignment self=originalException is just (type incorrect) pointer assignment (which the compiler and runtime will not check as you've used id as the type) - this won't make CustomException out of an NSException.

To achieve what you want replace self=originalException with

[super initWithName:[originalException name]
       reason:[originalException reason]
       userInfo:[originalException userInfo]]

and then continue to initialize the fields you've added in CustomException.


[*] In Objective-C it is possible in some cases to correctly convert a class instance into a subclass instance, but don't do it without very very very very good reason. And if you don't know how you shouldn't even be thinking of it ;-)

CRD
  • 52,522
  • 5
  • 70
  • 86
  • OO doesn't support down-casting a parent concrete type to a child type. However, this question is talking about copying. In C++, you can answer this question like this: http://cpp.sh/3ar6m – John K Feb 16 '17 at 20:48