尝试块-捕获可以嵌套到任何所需的级别。异常将按照相反的顺序处理,即最里面的异常处理将首先进行。
在下面的示例中,内部try块检查两个变量中的任何一个是否为非数字,如果为非数字,则抛出用户定义的异常。如果分母为0,则外部try块将引发DivisionByZeroError。否则,将显示两个数字的除法。
<?php class myException extends Exception{ function message(){ return "error : " . $this->getMessage() . " in line no " . $this->getLine(); } } $x=10; $y=0; try{ if (is_numeric($x)==FALSE || is_numeric($y)==FALSE) throw new myException("Non numeric data"); } catch (myException $m){ echo $m->message(); return; } if ($y==0) throw new DivisionByZeroError ("Division by 0"); echo $x/$y; } catch (DivisionByZeroError $e){ echo $e->getMessage() ."in line no " . $e->getLine(); } ?>
输出结果
显示以下输出
Division by 0 in line no 19
将任一变量更改为非数值
error : Non numeric data in line no 20
如果两个变量均为数字,则打印其除法