1.try catch 捕捉不到fatal error致命错误
2.只有抛出异常才能被截获,如果异常抛出了却没有被捕捉到,就会产生一个fatal error
3.父类可以捕获子类抛出的异常
class ExceptionNew extends Exception{ } function try_throw($type) { if ($type == 1) { throw new ExceptionNew("sunyue"); } } try { try_throw(1); } catch (Exception $e) { echo $e->getMessage(); }
4.try中的代码一旦抛出异常,代码将停止运行,直接执行catch中的代码
5.多个catch捕获多个异常
PHP将查询一个匹配的catch代码块。如果有多个catch代码块,传递给每一个catch代码块的对象必须具有不同类型(或者可以用同一父类去捕获,这样只要一个catch就可以了),这样PHP可以找到需要进入哪一个catch代码块。当try代码块不再抛出异常或者找不到catch能匹配所抛出的异常时,PHP代码就会在跳转最后一个catch的后面继续执行。因为原则4,所以每次其实这能抛出一个异常,一个异常被捕获。
class ExceptionNew extends Exception{ } class MyException extends Exception{ } function try_throw($type) { if ($type == 1) { throw new ExceptionNew("sun"); } if($type > 0){ throw new MyException("yue"); } } try { try_throw(1); try_throw(2); }catch (ExceptionNew $e) { echo $e->getMessage(); echo "----ExceptionNew"; }catch (MyException $e) { echo $e->getMessage(); echo "----MyException"; }
上段代码执行结果:
sun----ExceptionNew
6. php7新增Throwable Interface
To catch any exception in PHP 5.x and 7 with the same code, you would need to add a catch block for Exception AFTER catching Throwable first. Once PHP 5.x support is no longer needed, the block catching Exception can be removed.
Virtually all errors in PHP 5 that were fatal, now throw instances of Error in PHP 7.
try { // Code that may throw an Exception or Error. } catch (Throwable $t) { // Executed only in PHP 7, will not match in PHP 5 } catch (Exception $e) { // Executed only in PHP 5, will not be reached in PHP 7 }
参考链接: