简体   繁体   中英

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

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;
    }
}

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){

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM