1. 存在多个set_error_handle 或 set_exception_handle 的时候,会如何处理?
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
return 1/$x;
}
function onException1($e){
echo "exception1\n";
echo $e->getMessage();
}
function onException2($e){
echo "lxx_exception2\n";
echo $e->getMessage();
}
set_exception_handler("onException1");
set_exception_handler("onException2");
try {
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
echo inverse(0) . "\n";
// Continue execution
//require("laruence.php")
上面代码的执行结果:
Caught exception: Division by zero.
exception2
Division by zero.
从执行结果可以发现:
(1)当存在多个set_exception_handler时,只执行最后一个
(2)try catch内的不会被set_exception_handler捕捉到
2.set_exception_handle 添加日志?
在set_exception_handle定义的exception函数中可以进行更灵活的日志记录,在打印exception信息的同时能够带上自定义的日志信息
3.@还能不能抑制住exception?
可以:
1 <?php
2 function inverse($x) {
3 if (!$x) {
4 throw new Exception('Division by zero.');
5 }
6 return 1/$x;
7 }
8 function onException1($e){
9 echo "Caught exception1\n" . $e->getMessage();
10 echo "\n";
11 }
12 function onException2($e){
13 echo "Caught exception2\n" .$e->getMessage();
14 echo "\n";
15 }
16
17 set_exception_handler("onException1");
18 set_exception_handler("onException2");
19 //$a = @inverse(0);
20 $file = fopen('a.txt', 'r');
21
22 try {
23 $file =@fopen('a.txt', 'r');
24 } catch (Exception $e) {
25 echo 'Caught exception: ', $e->getMessage(), "\n";
26 }
27
28 // Continue execution
29 //require("laruence.php")
30 ?>
第20行:fopen(‘a.txt’, ‘r’);加@前结果:
PHP Warning: fopen(a.txt): failed to open stream: No such file or directory in /root/test_php/test_exception.php on line 20
PHP Stack trace:
PHP 1. {main}() /root/test_php/test_exception.php:0
PHP 2. fopen() /root/test_php/test_exception.php:20
第二十行:fopen(‘a.txt’, ‘r’);加@后不输出任何内容,表明@可以抑制住;