1

所以我有简单的代码:

try{
    $mysqli = new mysqli($sql_login['host'], $sql_login['user'], $sql_login['password'] , $sql_login['database'], $sql_login['port'] );


    if($mysqli->connect_errno){
        throw new Exception("Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error);
    }

}
catch (Exception $e) {
    echo 'Exception: ',  $e->getMessage(), "\n";
}

问题是 php 返回错误和异常。在 java 中是否有类似 throw 和 throws 的东西?

4

3 回答 3

1

您可以从安装自己的错误处理开始。一种将 PHP 错误转换为异常的方法。在脚本的开头执行此操作。像这样的东西:

/*
|--------------------------------------------------------------------------
| Alternative error handler
|--------------------------------------------------------------------------
|
| See: http://php.net/manual/en/function.set-error-handler.php
|
*/
function my_error_handler($errno, $errstr, $errfile, $errline)
{
    if (!(error_reporting() & $errno))
    {
        // This error code is not included in error_reporting
        return;
    }
    throw new ErrorException( $errstr, $errno, 0, $errfile, $errline );
}
ini_set('display_errors', FALSE);
set_error_handler("my_error_handler");

现在您可以使用异常作为主要的错误处理机制。您现在需要做的就是在脚本中的正确位置捕获异常并自己显示错误。

您还可以扩展此机制以包括断言处理:

/*
|--------------------------------------------------------------------------
| Assert handling
|--------------------------------------------------------------------------
|
|   See: http://php.net/manual/en/function.assert.php 
|
*/
function my_assert_handler($file, $line, $code)
{
    throw new Exception( "assertion failed @$file::$line($code)" );
}
assert_options(ASSERT_ACTIVE,     1);
assert_options(ASSERT_WARNING,    0);
assert_options(ASSERT_BAIL,       0);
assert_options(ASSERT_QUIET_EVAL, 0);
assert_options(ASSERT_CALLBACK, 'my_assert_handler');

并且只接受 PHP 不是 Java 或 C++。这是一个不一致的混乱。

于 2012-08-06T11:41:39.123 回答
0

您可以使用 PHP 的set_error_handler().

于 2012-08-06T11:24:52.803 回答
0

在连接的呼叫前面放一个@符号。这将抑制错误消息。

于 2012-08-06T11:29:02.843 回答