Php 为什么我们需要一个错误处理类或函数?

Php 为什么我们需要一个错误处理类或函数?,php,error-handling,Php,Error Handling,如果我们可以借助控制结构来处理错误,为什么我们需要用于错误处理的类和函数 比如,;我可以用PHP编写一个类似这样的错误处理类代码 <?php $number1=100; $number2=0; try { if ($number2==0){ throw new Exception("In the division process, the divisor cannot be zero.", 1); } echo $number1

如果我们可以借助控制结构来处理错误,为什么我们需要用于错误处理的类和函数

比如,;我可以用PHP编写一个类似这样的错误处理类代码

<?php
    $number1=100;
    $number2=0;

    try {

    if ($number2==0){
    throw new Exception("In the division process, the divisor cannot be zero.", 1);
    }

    echo $number1/$number2;
    } catch (Exception $error) {
    echo $error->getMessage();
    }
?>
因此,我可以编写与下面相同的代码,甚至更短:

<?php
    $number1=100;
    $number2=0;

    if ($number2==0){
    echo "In the division process, the divisor cannot be zero.";
    } else {
    echo $number1/$number2;
    }
?>

那么,为什么我们需要用于错误处理的类和函数呢?

因为如果您有100行代码,并且您希望其中25行/段代码失败,那么您需要编写25条if/else语句。对于错误处理,它只是:

<?php
try
{
    //100 lines of codes
}
catch(\Exception $e)
{
    //echo $e->getMessage();
    //echo $e->getLine();
    var_dump($e->getTrace());
}

因为有一件事你总是可以信赖的,那就是用户会找到一些巧妙的方法来破坏东西。。。你做梦也想不到的方式是可能的
In the division process, the divisor cannot be zero.
<?php
try
{
    //100 lines of codes
}
catch(\Exception $e)
{
    //echo $e->getMessage();
    //echo $e->getLine();
    var_dump($e->getTrace());
}