<?php
try {
$mgr = new CommandManager();
$cmd = $mgr->getCommandObject("realcommand");
$cmd->execute();
} catch (Exception $e) {
print $e->getMessage();
exit();
}
?>将要执行的代码放入TRY块中,如果这些代码执行过程中某一条语句发生异常,则程序直接跳转到CATCH块中,由$e收集错误信息和显示
try {
$mgr = new CommandManager();
$cmd = $mgr->getCommandObject("realcommand");
$cmd->execute();
} catch (Exception $e) {
print $e->getMessage();
exit();
}
?>将要执行的代码放入TRY块中,如果这些代码执行过程中某一条语句发生异常,则程序直接跳转到CATCH块中,由$e收集错误信息和显示
把可能发生的异常的代码段放入try里面,然后catch是处理异常的语句,如:http://cn2.php.net/manual/zh/language.exceptions.php,这里有详细的介绍。摘取一段:
<?php
try {
$error = 'Always throw this error';
throw new Exception($error); // 从这里开始,tra 代码块内的代码将不会被执行
echo 'Never executed';} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}// 继续执行
echo 'Hello World';
?>
我也是才接触php 不久,尝试过try..catch,但是请看下面测试用的代码
<?php
try{
echo "phpinfo()"
}catch(Exception $e){
echo "1";
}
?>
我想要达到的效果是如果 try 里面出错则在屏幕上显示 1 但是却显示“Parse error: syntax error, unexpected '}', expecting ',' or ';' in E:\workSpace\Apache Software Foundation\Apache2.2\htdocs\workSpace\voteExample\test.php on line 4” 不知道能不能实现我说的效果呢?处理机制似乎和我原来的认识不一样?还是代码在哪里出现了问题?希望各位帮下忙