2013-02-24 56 views
14

下面是我在函数中的try catch语句。我还没有使用try catch语句,我想知道如何在try catch语句中返回值,并且应该在try和catch语句之后返回值或在try块中返回是否正确?尝试和赶上PHP应该在尝试块返回?

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

你试过了吗?这是绝对好 – Eric 2013-02-24 13:34:03

回答

16

返回在try块就可以了?

是的。如果您需要将值返回,请执行此操作。

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

}catch(Exception $e){ 

} 
+0

谢谢我只是困惑,如果它将被返回,即使异常被提出 – Yalamber 2013-02-24 13:46:23

+0

@askkirati:注意在'finally'块中返回 - 可能会表现奇怪 – Eric 2013-02-24 14:00:06

+0

@eric PHP没有最终子句: ) – 2013-02-25 20:17:10