私の質問は、PHPで例外をキャッチする正しい方法についてです。 PHP MongoDBのドライバの伴うexamplesに基づいて、私は次のスクリプト作成した :PHPとMongoDBで例外を正しくキャッチする方法
<?php
try {
$mng = new MongoDB\Driver\Manager("mongodb://localhost:2717");
$query = new MongoDB\Driver\Query([], ['sort' => [ 'name' => 1], 'limit' => 5]);
$rows = $mng->executeQuery("testdb.cars", $query);
foreach ($rows as $row) {
echo "$row->name : $row->price\n";
}
} catch (MongoDB\Driver\Exception\Exception $e) {
$filename = basename(__FILE__);
echo "The $filename script has experienced an error.\n";
echo "It failed with the following exception:\n";
echo "Exception:", $e->getMessage(), "\n";
echo "In file:", $e->getFile(), "\n";
echo "On line:", $e->getLine(), "\n";
}
?>
を例は、教育やPHP CLI上で実行するためのものです。 PHPのCLIでは、コンソール上ですべての例外を取得しますが、教訓的な目的のためにtry/catchブロックで例外を捕捉したいと考えました。
私はPHPより多くのJavaコードを見ているので、汎用のMongoDB\Driver\Exception\Exception
を捕まえることは良くありません。 Javaでは、特定の例外を捕捉し、異なる種類の例外に対して複数のtry/catchブロックを持ちます。
ドライバは、以下の例外があります。
MongoDB\Driver\Exception\AuthenticationException
MongoDB\Driver\Exception\BulkWriteException
MongoDB\Driver\Exception\ConnectionException
MongoDB\Driver\Exception\ConnectionTimeoutException
MongoDB\Driver\Exception\Exception
MongoDB\Driver\Exception\ExecutionTimeoutException
MongoDB\Driver\Exception\InvalidArgumentException
MongoDB\Driver\Exception\LogicException
MongoDB\Driver\Exception\RuntimeException
MongoDB\Driver\Exception\SSLConnectionException
MongoDB\Driver\Exception\UnexpectedValueException
MongoDB\Driver\Exception\WriteException
が、これはPHPで例外をキャッチするユダヤの方法は何ですか?
複数のcatchステートメントを追加することができますが、これはPHPでの例外をキャッチするための推奨方法は何ですか?もしそうなら、なぜですか? –