我通常通过返回false
来指示方法中的错误,但它并不总是以我的语义凝聚(取决于方法,false
可能是有效的返回)。什么时候最好在PHP中使用异常?
我研究过异常,我想知道他们是一种万能的解决方案吗?我应该返回false
哪里还可以?
我可能在这里完全没有意义,所以请耐心等待。
// My old way
function getProductById($id) {
if (! is_numeric($id)) {
return false;
}
}
// My consideration
function getProductById($id) {
if (! is_numeric($id)) {
throw new Exception('The id must be numerical!');
}
}
我回答了一个类似的问题,那里的答案可能也有用:http://stackoverflow.com/questions/1069617/would-i-want-to-throw-an-exception-or-an-error -in-this-php-script/1069640 – soulmerge 2009-11-27 06:13:48