如何在mysql数据库连接中使用抛出异常

我遇到了这个:-

PHP 错误处理:die() Vs trigger_error() vs 抛出异常

并理解抛出异常更好

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

How can i replace die and use throw exception here in this code:-

<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_db = "localhost";
$database_db = "database";
$username_db = "root";
$password_db = "password";
$db = mysqli_connect($hostname_db, $username_db, $password_db) or die("Unable to connect with Database"); 
?>

推荐答案

try
{
    if ($db = mysqli_connect($hostname_db, $username_db, $password_db))
    {
        //do something
    }
    else
    {
        throw new Exception('Unable to connect');
    }
}
catch(Exception $e)
{
    echo $e->getMessage();
}

相关文章