【问题标题】:Exceptions in php, please explain [closed]php中的异常,请解释[关闭]
【发布时间】:2012-04-18 20:07:48
【问题描述】:

总的来说,我对编程很陌生,在阅读有关 PHP 的文章时,我看到了 try {} 和 catch {},想知道是否有人可以帮助我理解他们的意思?

【问题讨论】:

标签: php try-catch


【解决方案1】:

异常入门级入门:

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 块中放置函数/方法调用,您可以控制应用程序的流程执行。

【讨论】:

    【解决方案2】:

    PHP 有很好的文档 - 你应该从那里开始:

    http://php.net/manual/en/language.exceptions.php

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-10
      • 2013-03-15
      • 2014-09-24
      • 1970-01-01
      • 1970-01-01
      • 2013-11-04
      • 2014-08-05
      • 1970-01-01
      相关资源
      最近更新 更多