Title, will everyone use PHP exceptions, how to use
Some articles on the net, are introduced grammar, did not share how to really use good PHP exceptions.
It feels like PHP's abnormal mechanism is not as good as C++/java.
Reply content:
Title, will everyone use PHP exceptions, how to use
Some articles on the net, are introduced grammar, did not share how to really use good PHP exceptions.
It feels like PHP's abnormal mechanism is not as good as C++/java.
Because of the historical reasons PHP many built-in functions are no exception, but by returning false/-1 and so on to express the exception, resulting in developers are also accustomed to take the return value rather than the exception to distinguish (and the return value of the PHP function and array are so flexible)
After saying not to use the reason for the exception (although not to say the whole), then say why the exception is worth using. The first thing to note is that only the syntax, the latest version of the PHP exception, and Java is no different.
1. Richer error messages. Using a return value, such as False/-1, only lets us know that an exception has occurred, but we do not know what the exception was. Even by returning different status codes to different exceptions, it is still not as intuitive as the exception class. We can use the class name of the exception itself to determine what is the exception, through the exception class message to save a more detailed explanation, most importantly, we can use the exception of the error stack to determine which file is the first few lines of what function has been the problem, who went to call it .
2. Ensure that the caller handles the exception. If your function returns a normal value, it may be inadvertent, or it may be due to version compatibility issues (the caller is developing based on your old version of the function, and you have a new error state code in the new version of the function), and so on, the caller ignores the error you returned. That could cause the whole program to have problems that are difficult to spot. exceptions ensure that the caller has to deal with it .
3. Make your code logic clearer. Imagine that if there is no finally, an exception is detected for each return, and it is painful to write the resource again after each exception.
I wrote the framework by catching the exception to display the error page, other places I am basically no exception.
try { require_once ($some _file_path),} catch (Exception $e) { $smarty->assign ("error", $e->getmessage () ); $smarty->display ("Error.tpl");}