Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code compiles without any error when missed return statement from catch block

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?

like image 489
gagarwal Avatar asked May 28 '14 00:05

gagarwal


1 Answers

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.

like image 87
JoeFryer Avatar answered Oct 19 '22 10:10

JoeFryer