php对异常的处理与java一样,用到的是try{}catch(){}
定义顶级异常处理器用到的函数是
set_exception_handler("My_exception");
这里的My_expection是开发者自定义的异常处理函数,既顶级异常处理器,只有当程序中没有函数来处理异常才有顶级异常处理器来处理异常,如果没有定义顶级异常处理器,则由系统默认的异常处理器来处理异常
举例说明:
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<span style="color: #000000;">php </span><span style="color: #008080;">set_exception_handler</span>("My_expection"<span style="color: #000000;">); </span><span style="color: #0000ff;">function</span><span style="color: #000000;"> My_expection(){ </span><span style="color: #0000ff;">echo</span> "这里是顶级异常处理器"<span style="color: #000000;">; } </span><span style="color: #0000ff;">try</span><span style="color: #000000;">{ nohello(</span>"hello"<span style="color: #000000;">); }</span><span style="color: #0000ff;">catch</span>(<span style="color: #0000ff;">Exception</span> <span style="color: #800080;">$e</span><span style="color: #000000;">){ </span><span style="color: #0000ff;">throw</span> <span style="color: #800080;">$e</span><span style="color: #000000;">; } </span><span style="color: #0000ff;">function</span> nohello(<span style="color: #800080;">$nohello</span><span style="color: #000000;">){ </span><span style="color: #0000ff;">if</span>(<span style="color: #800080;">$nohello</span> == "hello"<span style="color: #000000;">){ </span><span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span> <span style="color: #0000ff;">Exception</span>("不能输入hello"<span style="color: #000000;">); }</span><span style="color: #0000ff;">else</span><span style="color: #000000;">{ </span><span style="color: #0000ff;">echo</span> "输入成功"<span style="color: #000000;">; } }</span>?>
转载自:http://blog.sina.com.cn/s/blog_641d5693010121cr.html