[PHP错误异常]⑧--异常处理案例演示

2017-09-14  本文已影响11人  子木同
Paste_Image.png Paste_Image.png Paste_Image.png Paste_Image.png Paste_Image.png Paste_Image.png
<?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);
?>
Paste_Image.png
<?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();
}

?>
Paste_Image.png

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();
}
?>
Paste_Image.png
上一篇 下一篇

猜你喜欢

热点阅读