php抛出异常停止执行

时间:2014-06-18 15:12:25

标签: php exception

我有这段代码:

function divide($a,$b){
    try{
        if($b==0){
            throw new Exception("second variable can not be 0");
        }
        return $a/$b;
    }
    catch(Exception $e){
        echo $e->getMessage();
    }
}

echo divide(20,0);
echo "done";

当第二个参数为0时抛出异常。如何阻止done打印?

1 个答案:

答案 0 :(得分:4)

不要在divide()中捕获您的异常并在以后捕获它:

function divide($a,$b){
    if($b==0){
        throw new Exception("second variable can not be 0");
    }
    return $a/$b;
}

try {
    echo divide(20,0);
    echo "done";
} catch(Exception $e){
    echo $e->getMessage();
}