php – 如何在mysql数据库连接中使用throw异常

前端之家收集整理的这篇文章主要介绍了php – 如何在mysql数据库连接中使用throw异常前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我遇到过这个: –

PHP Error handling: die() Vs trigger_error() Vs throw Exception

并且理解抛出异常更好

如何在此代码中替换die并使用throw异常: –

  1. <?PHP
  2. # FileName="Connection_PHP_MysqL.htm"
  3. # Type="MysqL"
  4. # HTTP="true"
  5. $hostname_db = "localhost";
  6. $database_db = "database";
  7. $username_db = "root";
  8. $password_db = "password";
  9. $db = MysqLi_connect($hostname_db,$username_db,$password_db) or die("Unable to connect with Database");
  10. ?>
  1. try
  2. {
  3. if ($db = MysqLi_connect($hostname_db,$password_db))
  4. {
  5. //do something
  6. }
  7. else
  8. {
  9. throw new Exception('Unable to connect');
  10. }
  11. }
  12. catch(Exception $e)
  13. {
  14. echo $e->getMessage();
  15. }

猜你在找的PHP相关文章