0

所以我正在阅读关于扩展异常的 php 手册并阅读示例代码。我对以下代码的问题是:为什么var_dump($o)评估为null?是因为类的构造函数TestException抛出异常,因此不允许完成对象吗?我几乎可以肯定这就是原因。

不过这里是检查代码:

<?php
/**
 * Define a custom exception class
 */
class MyException extends Exception
{
    // Redefine the exception so message isn't optional
       public function __construct($message, $code = 0, Exception $previous = null) {
    // some code

    // make sure everything is assigned properly
    parent::__construct($message, $code, $previous);
}

// custom string representation of object
public function __toString() {
    return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}

public function customFunction() {
    echo "A custom function for this type of exception\n";
    }
}


/**
 * Create a class to test the exception
 */
class TestException
{
    public $var;

    const THROW_NONE    = 0;
    const THROW_CUSTOM  = 1;
    const THROW_DEFAULT = 2;

    function __construct($avalue = self::THROW_NONE) {

        switch ($avalue) {
            case self::THROW_CUSTOM:
                // throw custom exception
                throw new MyException('1 is an invalid parameter', 5);
                break;

            case self::THROW_DEFAULT:
                // throw default one.
                throw new Exception('2 is not allowed as a parameter', 6);
                break;

            default: 
                // No exception, object will be created.
                $this->var = $avalue;
                break;
        }
    }
}


// Example 1
try {
    $o = new TestException(TestException::THROW_CUSTOM);
} catch (MyException $e) {      // Will be caught
    echo "Caught my exception\n", $e;
    $e->customFunction();
} catch (Exception $e) {        // Skipped
    echo "Caught Default Exception\n", $e;
}

// Continue execution
var_dump($o); // Null
?>
4

1 回答 1

0

从 PHP 官方网站查看 PHP 异常。

例子:

<?php

class MyException extends Exception { }

class Test {
    public function testing() {
        try {
            try {
                throw new MyException('foo!');
            } catch (MyException $e) {
                /* rethrow it */
                throw $e;
            }
        } catch (Exception $e) {
            var_dump($e->getMessage());
        }
    }
}

$foo = new Test;
$foo->testing();

?>
于 2013-02-18T04:58:56.890 回答