





<?php
error_reporting(-1);
$num = NULL;
try {
$num = 3 / 0;
var_dump($num);
} catch (Exception $e) {
//没有抛出异常 不执行
echo $e->getMessage();
$num = 12;
}
echo "<hr/>";
echo "continue...";
var_dump($num);
?>

<?php
header("content-type;text/html;charset=utf-8");
error_reporting(-1);
try {
$num1 = 3;
$num2 = 0;
if ($num2 == 0) {
throw new Exception('0不能当做除数');
echo "this is a test";//不执行
} else {
$res = $num1 / $num2;
}
} catch (Exception $e) {
echo $e->getMessage();
}
?>

Php不像java提供了很多异常类,所以很多异常都会当成错误。
要想变错误为抛出异常,需要
手动throw异常对象
<?php
header("content-type;text/html;charset=utf-8");
error_reporting(-1);
try {
if ($username == 'king') {
echo "hello king";
} else {
throw new Exception('非法管理员');
}
} catch (Exception $e) {
echo $e->getMessage();
echo "<hr/>";
die();
}
?>

网友评论