简体   繁体   English

在PHP中使用odbc_exec时使用try-catch语句的异常行为

[英]Unexpected behavior using try-catch statement when using odbc_exec in PHP

In an earlier question , I got the advice to use a try-catch statement on an odbc_connect call. 前面的问题中 ,我得到了在odbc_connect调用上使用try-catch语句的建议。 Well, said and done, that's what I've tried to do. 好了,说完了,这就是我试图做的。

The following code, which tries to connect to a database using bogus login information, does not work as excpected. 以下代码尝试使用虚假的登录信息连接到数据库,但无法正常运行。

<?php
  try
  {
    odbc_connect('BogusDatabase','BogusUser','BogusPassword');
  }
  catch (Exception $e)
  {
    echo "Something went wrong!";
  }
?>

I would expect the output to be a string saying "Something went wrong!". 我希望输出是一个字符串,指出“出了点问题!”。 Instead I get this: 相反,我得到这个:

该死的!我不要这个!

I'm using Wampserver to run my PHP code. 我正在使用Wampserver运行我的PHP代码。 I don't know if this is a part of the problem. 我不知道这是否是问题的一部分。

As @Aurimas said, you have to use error_handler to do that. 正如@Aurimas所说,您必须使用error_handler来做到这一点。 http://php.net/manual/en/function.set-error-handler.php http://php.net/manual/zh/function.set-error-handler.php

this function look after the errors that occured in your script and call a function that you provide each time an error is throwed. 此函数将照顾脚本中发生的错误,并在每次引发错误时调用您提供的函数。

A simple handler is 一个简单的处理程序是

function($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}

It throws a ErrorException each time an error is raised in your script. 每次在脚本中引发错误时,都会引发ErrorException。 so this whole script will behave as you expect : 因此,整个脚本的行为将与您期望的一样:

 set_error_handler(function($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
 });
 try
{
  odbc_connect('BogusDatabase','BogusUser','BogusPassword');
}
catch (Exception $e)
{
  echo "Something went wrong!";
}

On PHP manual Exeptions : 在PHP手册

Internal PHP functions mainly use Error reporting, only modern Object oriented extensions use exceptions. 内部PHP函数主要使用错误报告,仅现代的面向对象的扩展使用异常。 However, errors can be simply translated to exceptions with ErrorException 但是,可以使用ErrorException将错误简单地转换为异常。

Take a look at the ErrorException and set your custom error handle, to catch these errors. 看一下ErrorException并设置您的自定义错误句柄,以捕获这些错误。

The function is not throwing an Exception. 该函数未引发异常。 Instead, it's triggering a warning. 相反,它会触发警告。 If you don't want warnings to display, you can use the error_reporting() to display only actual errors. 如果您不想显示警告,则可以使用error_reporting()仅显示实际错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM