1.11PHP语言的异常(Exception)语句

throw语句

throw 表达式;

try语句

//句法一
try {
    //可能会发生异常的语句
} catch(异常类型 e) {
    //处理异常 e
}
//句法二
try {
    //可能会发生异常的语句
} catch(异常类型 e) {
    //处理异常 e
} finally {
    //不管是否有异常捕获,finally子句中的代码都会执行
}

示例 #1 抛出一个异常

<?php
function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    return 1/$x;
}

try {
    echo inverse(5) . "\n";
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo "Hello World\n";
?>
//输出
0.2
Caught exception: Division by zero.
Hello World

示例 #2 带 finally 块的异常处理

<?php
function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    return 1/$x;
}

try {
    echo inverse(5) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
} finally {
    echo "First finally.\n";
}

try {
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
} finally {
    echo "Second finally.\n";
}

// 继续执行
echo "Hello World\n";
?>
//输出
0.2
First finally.
Caught exception: Division by zero.
Second finally.
Hello World

原创文章,作者:huoxiaoqiang,如若转载,请注明出处:https://www.huoxiaoqiang.com/back/php/4973.html

发表评论

登录后才能评论