2013-02-24 40 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