ale
ale

Reputation: 11820

Good error handling practice in PHP - what to do if function doesn't return when it should

I'm looking to improve error handling and debugging in my PHP programs and need some advice. Let's say I have this function (which as absolutely no use.. just made it up):

function foo($bar) {
   foreach($bar as $x):
      if($x == 'something') {
         return 'found something'
      }
   endforeach;
}

The above wouldn't be allowed in say C if I told C that the function is meant to return something. This is because $x might never equal 'something'.

Would this be one step towards improving my function?

function foo($bar) {
   foreach($bar as $x):
      if($x == 'something') {
         return 'found something'
      }
   endforeach;
   throw new Exception('some exception');
}

It still doesn't ensure the function returns though.. unless throwing a new Exception returns but I don't think so. Is there no better way or error handling than doing this? :

function foo($bar) {
   foreach($bar as $x):
      if($x == 'something') {
         return 'found something'
      }
   endforeach;
   throw new Exception('some exception');
   return -1; 
}

and then checking whether the function returns -1 elsewhere in the code?

Thanks :).

Upvotes: 0

Views: 121

Answers (2)

Sumair Zafar
Sumair Zafar

Reputation: 98

function Demo()
{
    try
    {
        // Your logic here
    }
    catch(Exception $e)
    {
        error_log($e->getMessege(),3,'error.log');
    }
}

Upvotes: 0

BoltClock
BoltClock

Reputation: 723598

Throwing an exception from a function doesn't allow the function to return. Even if it does, you won't get a chance to look at the return value either, as PHP will demand that the exception be handled in a catch block right away.

If you need to return -1 if $x can never be equal to 'something', don't throw any exceptions from within the function. But if you're going to throw an exception from the calling code when it returns -1, you may as well forget returning that value. Just throw the exception directly, and handle it in a catch block in your calling code.

Useful reading: PHP manual on exception handling

Upvotes: 2

Related Questions