Bu iç içe geçmiş durumlar yakalamak nasıl?

2 Cevap

Örnek: Ben bir istisna atar bir PDO yöntemini kullanın. Başka bir şey yanlış giderse deneyin blok içinde, ben de kendi özel durum atar. Şimdi ayrı ayrı PDOException ve kendi özel durum işlemek istiyorum. Nasıl o iş yapmak için bu ayrı olabilir?

   public function prepare(string $sql, array $params) {
    try {
        $prepared = $this->dbh->prepare($sql); // may throw PDOException
        $i = 1;
        foreach ($params as $param) {
        $ok = $prepared->bindParam($i, $param);
        if (!$ok) {
            throw new Exception("Unable to bind parameter (" . $param . ") to prepared statement: " . $sql);
        }
        $i++;
        }
    } catch (PDOException $e) {
        throw new Exception("DB:prepare(): Could not prepare statement. " . $e->getMessage());
    }
    return $prepared;
   }

Ben bir dosyaya herhangi bir istisna oturum ilgilenir küresel bir hata işleyicisi var unutmayın. Bunun yerine bir günlük dosyasına doğrudan yazma benim kendi istisnalar atmak bu yüzden (bu şekilde, ben de geri izleme olsun).

2 Cevap

Bu gibi çeşitli catch blokları kullanabilirsiniz:

try {
    // ...
} catch (PDOException $e) {
    // Handle the PDOException, with some specific code
} catch (Exception $e) {
    // Handle any other kind of Exception 
    // that has not already been catched by 
    // one of the previous(es) catch block
}

Ama önce "en özel" durum türü koymak zorunda notu - Exception sonuncusu olmak zorunda anlamına gelir.


Here are a couple of articles / blog-posts that might interest you, about exceptions and PHP :

Birden catch es! Ya da tek yakalamak bir Exception ve tip kontrol edin.