当一个异常被抛出时,其后(译者注:指抛出异常时所在的代码块)的代码将不会继续执行,而 php 就会尝试查找第一个能与之匹配的 catch。如果一个异常没有被捕获,而且又没用使用 set_exception_handler() 作相应的处理的话,那么 php 将会产生一个严重的错误,并且输出 uncaught exception ... (未捕获异常)的提示信息。
注意 hp 内部函数主要使用错误报告, 只有现代面向对象的扩展才使用异常。但错误可以很容易的通过errorexception转换为异常。
php标准库 (spl) 提供了许多内建的异常类。
example #1 抛出一个异常
<?php function inverse($x) { if (!$x) { throw new exception('division by zero.'); } else return 1/$x; } try { echo inverse(5) . "\n"; echo inverse(0) . "\n"; } catch (exception $e) { echo 'caught exception: ', $e->getmessage(), "\n"; } // continue execution echo 'hello world'; ?>
以上例程会输出:
0.2
caught exception: division by zero.
hello world
example #2 嵌套的异常
<?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(); ?>
以上例程会输出:
string(4) foo!
