0

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

4

2 回答 2

2

例外的入门级入门:

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

于 2012-04-05T04:24:50.147 回答
1

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

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

于 2012-04-05T04:14:45.130 回答