NSException raise:format: as the last statement in a method

a 夏天 提交于 2019-12-01 19:03:30

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.

Replacing [exception raise]; with @throw exception; is functionally the same thing and will prevent the warning (see: Throwing Exceptions).

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!