是否有静态方法在php中引发异常 [英] Is there a static way to throw exception in php

查看:74
本文介绍了是否有静态方法在php中引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在php中是否有引发异常的静态方式?

Is there a "static" way of throwing an exception in php?

我需要在mysql查询失败时引发异常。

I need to throw an exception when a mysql query fails.

我尝试过这个:

$re=@mysql_query( $query ) or throw new Exception(' Query Failed ');

但它不起作用。

我正在使用基于 throwException()函数在 PHP:异常手册 中的注释中,但是我想知道是否存在无需创建类的静态方法。

And I'm using a function based on the throwException() function from this comment at PHP: Exceptions manual, but I would like to know if there is a static way for doing this without making a class.

推荐答案

您将无法直接执行或抛出新的Exception(); ,因为 throw 是语句,而不是表达式。由于实际上是一个运算符,因此它希望其操作数是表达式(计算结果为某些值的事物)。

You won't be able to directly do or throw new Exception(); because throw is a statement, not an expression. Since or is really an operator, it expects its operands to be expressions (things that evaluate to some values).

您必须改为:

$re = mysql_query($query);

if (!$re) {
    throw new Exception('Query Failed');
}

如果您尝试使用 throwException( )由该PHP手动注释提出的功能,正如webbiedave指出的那样,注释是您需要调用该函数,而不是直接调用 throw 语句,就像这样:

If you're trying to use the throwException() function proposed by that PHP manual comment, as webbiedave points out the comment is saying that you need to call that function instead of the throw statement directly, like this:

$re = mysql_query($query) or throwException('Query Failed');

PHP中没有规则说需要从类方法中抛出异常。只要有某种方法可以捕获该异常,就可以了。如果您是想在不使用 Exception 类的情况下引发异常,那么必须这样做。异常是天生的对象;您不能抛出不是对象的异常(或不从 Exception 类继承的异常)。

There's no rule in PHP that says you need to throw exceptions from a class method. As long as there's some way to catch that exception you're fine. If you mean you want to throw exceptions without using the Exception class, well, you have to. Exceptions are objects by nature; you can't throw an exception that isn't an object (or doesn't inherit from the Exception class).

如果您不想引发异常,但会引发从PHP中经常看到的错误(通知,警告和致命错误),请使用 trigger_error()

If you don't want to throw exceptions but raise the kind of error you often see from PHP (notices, warnings and fatal errors), use trigger_error().

$re = mysql_query($query);

if (!$re) {
    trigger_error('Query Failed', E_USER_ERROR);
}

这篇关于是否有静态方法在php中引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆