php手动异常示例

php手动异常示例,php,exception,manual,extending,Php,Exception,Manual,Extending,因此,我正在阅读关于扩展异常的php手册并阅读示例代码。关于以下代码,我的问题是:var\u dump($o)为什么计算为null?是否因为类TestException的构造函数抛出异常,因此不允许完成对象?我几乎可以肯定这就是原因 然而,以下是检查代码: <?php /** * Define a custom exception class */ class MyException extends Exception { // Redefine the exception s

因此,我正在阅读关于扩展异常的php手册并阅读示例代码。关于以下代码,我的问题是:
var\u 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
?>

例如:

<?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();

?>