简体   繁体   English

尝试用PHP捕获 - 我应该在'try'块中返回吗?

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

Below is my try catch statement in a function. 下面是我在函数中的try catch语句。 I have not used try catch statement much, and I wanted to know how to return values in a try catch statement. 我没有多使用try catch语句,我想知道如何在try catch语句中返回值。 Should I return a value after the try and catch statement or is returning in the try block OK? 我应该在try和catch语句之后返回一个值,还是在try块中返回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? 在try块中返回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){

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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