php5.3から使える例外チェーンのメモ
<?php class FooException extends Exception { } class BarException extends Exception { } class BazException extends Exception { } function foo() { throw new FooException('foo error'); } function bar() { try { foo(); } catch (Exception $e) { throw new BarException('bar error', 0, $e); } } function baz() { try { bar(); } catch (Exception $e) { throw new BazException('baz error', 0, $e); } } // main try { baz(); } catch (Exception $e) { echo 'CATCH!', PHP_EOL; echo $e; }
$ php ./exception_test.php CATCH! exception 'FooException' with message 'foo error' in /Users/kalibora/src/php/exception_test.php:13 Stack trace: #0 /Users/kalibora/src/php/exception_test.php(18): foo() #1 /Users/kalibora/src/php/exception_test.php(26): bar() #2 /Users/kalibora/src/php/exception_test.php(33): baz() #3 {main} Next exception 'BarException' with message 'bar error' in /Users/kalibora/src/php/exception_test.php:20 Stack trace: #0 /Users/kalibora/src/php/exception_test.php(26): bar() #1 /Users/kalibora/src/php/exception_test.php(33): baz() #2 {main} Next exception 'BazException' with message 'baz error' in /Users/kalibora/src/php/exception_test.php:28 Stack trace: #0 /Users/kalibora/src/php/exception_test.php(33): baz() #1 {main}
例外をラップすべきかどうかは考える余地があるとして、
ラップしたい場合には便利。