Why does following code compile fine without any error?
- (NSArray *) getSomeObjects
{
@try
{
NSArray * arrayToReturn = [NSArray array];
// Perform some oprations on arrayToReturn
return arrayToReturn;
}
@catch (NSException * exception)
{
// Uh Oh!!! I got an exception.
}
// See I am not returning anything from here
// and code still compiles fine without any
// compiler error.
}
On any exception I need to return an empty NSArray after my @catch is executed.
Is there any compiler flag in Xcode to warn these missing return statements as errors?
As far as the compiler is concerned, the return
statement in the @try
block is always reached during normal execution. It doesn't think 'oh, there might be an exception on this line, therefore the return
statement on the next line will never get reached'. Otherwise, there would need to be a warning for all methods with a return value :)
The try/catch block doesn't change this.
At least, this is how I understand it. I welcome anyone to correct me/expand on this/explain it better.
Edit to address this:
On any exception I need to return an empty NSArray after my @catch is executed.
You can put another return
statement in your @catch
block, for if there is an exception.
Interestingly, you do not want to put another return
in the @finally
block for this purpose, as this will override/supersede/replace the return
in the @try
block, even if the one in the @try
block is reached normally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With