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

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容