PHP手册-自定义异常Exception

class MyException extends Exception {
	public function __construct($message, $code = 0) {
		parent::__construct($message, $code);
	}

	public function __toString() {
		return __CLASS__.':['.$this->code.']:'.$this->message.'\n';
	}

	public function customFunction() {
		echo '自定义错误类型';
	}
}

//自定义函数,在何时抛出异常需自己声明
class TestException {
	public $var;

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

	function __construct($avalue = self::THROW_NONE) {
		//自写逻辑抛出异常try catch会捕获
		switch($avalue) {
		case self::THROW_CUSTOM:
			throw new MyException('1 is an invalid parameter', 5);
			break;
		case self::THROW_DEFAULT:
			throw new Exception('2 isnt allowed as a parameter', 6);
			break;
		default:
			$this->var = $avalue;
			break;
		}
	}

}

try {
    $o = new TestException(TestException::THROW_CUSTOM);
} catch (MyException $e) {      // 捕获异常
    echo "Caught my exception\n", $e;
    $e->customFunction();
} catch (Exception $e) {        // 被忽略
    echo "Caught Default Exception\n", $e;
}

展开阅读全文

没有更多推荐了,返回首页