Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try and catch in PHP - should I return in the 'try' block?

Tags:

php

try-catch

Below is my try catch statement in a function. I have not used try catch statement much, and I wanted to know how to return values in a try catch statement. Should I return a value after the try and catch statement or is returning in the try block OK?

function createBucket($bucket_name) {
    if ($this->isValidBucketName($bucket_name)) {
        if ($this->doesBucketExist($bucket_name)) {
            return false;
        }
        else {
            try {
                $this->s3Client->createBucket(
                        array(
                            'Bucket' => $bucket_name,
                            'ACL' => CannedAcl::PUBLIC_READ
                        // Add more items if required here
                ));
                return true;
            }
            catch (S3Exception $e) {
                $this->airbrake->notifyOnException($e);
                return false;
            }
        }
    }
    else {
        $this->airbrake->notifyOnError('invalid bucket name');
        return false;
    }
}
like image 774
Yalamber Avatar asked Feb 24 '13 13:02

Yalamber


1 Answers

is returning in the try block OK?

Yes, it is. If you need to return the value there, do it.

try {
  function_that_throws_exception();
  return true;   // <-- This will never happen if an exception is raised

}
catch(Exception $e){

}
like image 169
nice ass Avatar answered Oct 11 '22 11:10

nice ass