【发布时间】:2012-04-18 20:07:48
【问题描述】:
总的来说,我对编程很陌生,在阅读有关 PHP 的文章时,我看到了 try {} 和 catch {},想知道是否有人可以帮助我理解他们的意思?
【问题讨论】:
-
这是超级基础的,我建议你拿起一本好的PHP书开始阅读,这样你就会了解编程的基础。
总的来说,我对编程很陌生,在阅读有关 PHP 的文章时,我看到了 try {} 和 catch {},想知道是否有人可以帮助我理解他们的意思?
【问题讨论】:
异常入门级入门:
function doSomething($arg1)
{
if (empty($arg1)) {
throw new Exception(sprintf('Invalid $arg1: %s', $arg1));
}
// Reached this point? Sweet lets do more stuff
....
}
try {
doSomething('foo');
// Above function did not throw an exception, I can continue with flow execution
echo 'Hello world';
} catch (Exception $e) {
error_log($e->getMessage());
}
try {
doSomething();
// Above function DID throw an exception (did not pass an argument)
// so flow execution will skip this
echo 'No one will never see me, *sad panda*';
} catch (Exception $e) {
error_log($e->getMessage());
}
// If you make a call to doSomething outside of a try catch, php will throw a fatal
// error, halting your entire application
doSomething();
通过在 try/catch 块中放置函数/方法调用,您可以控制应用程序的流程执行。
【讨论】:
PHP 有很好的文档 - 你应该从那里开始:
【讨论】: