我可以声明一个 php 函数抛出异常吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3325294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I declare that a php function throws an exception?
提问by shay
Can I declare a function in php that throws an exception? For example:
我可以在 php 中声明一个抛出异常的函数吗?例如:
public function read($b, $off, $len) throws IOException
采纳答案by Lee Jarvis
I misread the question, see the answer below from Gilad (which should be accepted).
我误读了这个问题,请参阅以下 Gilad 的答案(应该接受)。
Previous answer:
上一个答案:
You could throw a new exception from the body of the function. It's all described here
您可以从函数体中抛出一个新的异常。这一切都在这里描述
Example:
例子:
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
else return 1/$x;
}
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
// Continue execution
echo 'Hello World';
?>
回答by Gilad
You can use @throws in the PHPDoc comment, and the IDE will recognize this function as throwing an exception, when viewing the doc, however unlike Java it will not force you to implement the Try{}catch block. Maybe future versions of the IDE (I am using InteliJ 11) will mark those places where try{}catch is expected, that same as it already do with the JavaScript types marked by doc (e.g. String}) when recognizing inconsistency.
您可以在 PHPDoc 注释中使用 @throws,在查看文档时,IDE 会将此函数识别为抛出异常,但与 Java 不同的是,它不会强制您实现 Try{}catch 块。也许未来版本的 IDE(我使用的是 InteliJ 11)会标记那些需要 try{}catch 的地方,这与它在识别不一致时对由 doc(例如 String})标记的 JavaScript 类型所做的相同。
In short, using Doclet like when codding with scripting languages (PHP, JavaScript..), is turn to be complementary tool for safer programming in the case of non type-safe and non compiled languages.
简而言之,在使用脚本语言(PHP、JavaScript ..)进行编码时使用 Doclet,在非类型安全和非编译语言的情况下,成为更安全编程的补充工具。
like this:
像这样:
enter code here
/**
* Handle 'get' operations
* @abstract
* @param int $status reference for setting the response status
* @param String $body reference for setting the response data
* @return mixed
* @throws Exception if operation fail
*/
function get(&$status, &$body) {
}


回答by Jim W.
For a list of exceptions that come with the SPL: SPL Exceptions.
有关 SPL 附带的异常列表:SPL Exceptions。
If you want to create your own exception:
如果要创建自己的异常:
From the PHP Exceptionspage:
从PHP 异常页面:
The thrown object must be an instance of the Exception Classor a subclass of Exception. Trying to throw an object that is not will result in a PHP Fatal Error.
So yes, it is possible to create your own exceptions. Just a bit of reading will help you achieve what you want.
所以是的,可以创建自己的例外。只需要一点点阅读就能帮助你实现你想要的。

