【发布时间】:2011-07-29 20:53:55
【问题描述】:
考虑一个函数层次结构,函数 Four() 调用 Three(),后者调用 Two(),后者再次调用 One() 来完成工作:
Function One($x) {
if(!is_int($x)) {
throw Exception("X must be integer");
}
// .......... Do the Job ................
}
Function Two($x) {
if(!is_int($x)) {
throw Exception("X must be integer");
} else {
One($x);
}
}
Function Three($x) {
if(!is_int($x)) {
throw Exception("X must be integer");
} else {
Two($x);
}
}
Function Four($x) {
if(!is_int($x)) {
throw Exception("X must be integer");
} else {
Three($x);
}
}
如果我用一个字符串值调用四个,它会导致一个异常发生。
现在考虑只在父函数中有异常的代码。
Function One($x) {
if(!is_int($x)) {
throw Exception("X must be integer");
}
// .......... Do the Job ................
}
Function Two($x) {
One($x);
}
Function Three($x) {
Two($x);
}
Function Four($x) {
Three($x);
}
这里,我调用 Four() 并传递一个字符串,它也会导致发生异常。
那么哪一个是最佳实践,为什么?
当我开始编写代码时,我最终会编写很多异常处理,请帮助。
【问题讨论】:
-
其实php在抛出异常方面并没有像JAVA那么远。在java中,如果有可能引发异常,则必须使函数成为抛出函数,以便代码的用户实际上会看到可能存在异常。在 php 中,您将独自一人,而在第二个示例中,仅通过查看 Four 您将无法直接判断可能存在异常。所以第一个会是更好的做法。
-
我只在类方法中使用异常,在函数中我使用错误。
-
但是如果你做了一个很好的文档并声明这个特定的函数可能会在函数文档中抛出异常,那么第二个例子也应该没问题。