问题
I have this method:
+ (MHTwitterParser*)createParser:(NSString*)format {
if ([format compare:@"json"] == NSOrderedSame) {
return [[MHJsonTwitterParser alloc] init];
}
[NSException raise:@"Unknown format" format:@"Unknown format of parser"];
}
Compiler complains that:
Control may reach end of non-void function
It is just a warning, but it does not matter.
Obvious fix for that is to add for example return nil;
after the [NSException raise: ...
.
However, I think it is not needed (and is even misleading for readers), because the exception is thrown, so it is not true that "Control may reach end of non-void function". Or am I missing something ...? Is it only compiler imperfection or there is some considerable reason for this?
The compiler is Apple LLVM compiler 3.1
回答1:
The reason is simple.
For the compiler, the method [NSException raise: ...]
is a black box method. It doesn't know that the method will actually raise an exception.
If you compare it with Java or C++, their throw
statements are a language feature and the compiler knows exactly what will happen when it finds it. In Obj-C it's different and sometimes it depends on runtime conditions. Consider the following.
NSException* exception = nil;
if (someCondition) {
exception = [NSException exceptionWithName:...];
}
[exception raise];
The compiler won't know if the exception is really raised or not.
回答2:
Replacing [exception raise];
with @throw exception;
is functionally the same thing and will prevent the warning (see: Throwing Exceptions).
回答3:
The warning is there simply because not every path through the code ends with a return statement which the compiler recognizes as potentially problematic. That said, you probably shouldn't be throwing an exception here and should instead be generating an NSError
and returning nil
. The differences between exceptions and errors in objective-c are explained here and here.
来源:https://stackoverflow.com/questions/10400936/nsexception-raiseformat-as-the-last-statement-in-a-method