捕获 PHP 中的异常语法错误
我尝试在 PHP 中使用异常作为避免多个 if-then-else
块的方法。但是,当我尝试捕获异常时,我收到错误解析错误:语法错误,/directory/functions.php 第 66 行中意外的 T_CATCH
。我的投掷和接球动作是否有问题?
function doThis($sSchool, $sDivision, $sClass, $sUsername, $sCode,$query1,$query2)
{
connectDb();
global $dbConnection;
$sDivisionIdArray = mysqli_query($dbConnection,$query1);
if ($sDivisionIdArray==false){throw new Exception ();}
$sDisplayQueryArray = mysqli_query($dbConnection,$query2);
if ($sDisplayQueryArray==false){throw new Exception ();}
catch (Exception $e) // This is line 666
{echo ('Sorry, an error was encountered.');}
}
I'm trying to use exceptions in PHP as a way of avoiding multiple if-then-else
blocks. However, when I try to catch the exception, I get the error Parse error: syntax error, unexpected T_CATCH in /directory/functions.php on line 66
. Am I doing something wrong with my throwing and catching?
function doThis($sSchool, $sDivision, $sClass, $sUsername, $sCode,$query1,$query2)
{
connectDb();
global $dbConnection;
$sDivisionIdArray = mysqli_query($dbConnection,$query1);
if ($sDivisionIdArray==false){throw new Exception ();}
$sDisplayQueryArray = mysqli_query($dbConnection,$query2);
if ($sDisplayQueryArray==false){throw new Exception ();}
catch (Exception $e) // This is line 666
{echo ('Sorry, an error was encountered.');}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
未经尝试就无法使用 catch。
You can't use catch without a try.
您忘记了
try
语句。You forgot the
try
statement.为了增加您对 PHP 异常的了解,您还可以在抛出的异常中传递消息,这些消息可以被捕获并存储(如果您选择)。
如果您未能在引发的异常周围包含 try/catch 块,则可以选择在代码中包含默认异常处理程序,该处理程序将捕获使用 set_exception_handler。这可用于标准化 404/500 错误页面,也可用于适当处理错误并可能将它们记录到文件中。
To increase your knowledge of PHP exceptions, you may also pass messages in your thrown exceptions which can be caught and stored (if you so choose).
If you fail to include try/catch blocks around a thrown exception, you could choose to include a default exception handler in your code which will catch all exceptions thrown using set_exception_handler. This can be used to standardize a 404/500 error page and also to handle errors appropriately and possible log them to a file.
其他答案指出缺少 try 块。我只是想提一下,使用异常进行流量控制并不总是一个好主意。除了概念问题(异常应该表明发生了一些不寻常的事情,必须予以处理,而不是作为美化的跳转),使用异常 可能效率较低。
Other answers have pointed out the lack of a try block. I just wanted to mention that using exceptions for flow control isn't always a great idea. Aside from the conceptual issue (exceptions should signal that something out of the ordinary happened which must be dealt with, not serve as a glorified goto), use of exceptions may be less efficient.