我有以下代码:

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打印?

最佳答案

不要在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();
}

09-30 16:49
查看更多