为什么不进入catch块而没有抛出异常

问题描述:

我是新来的PHP,我来自java的背景,我想知道为什么php不会直接在try块中发生异常而没有手动抛出异常。 例如为什么不进入catch块而没有抛出异常

<?php 
//create function with an exception 
function checkNum($number) { 
    if($number/0) { 
    throw new Exception("Value must be 1 or below"); 
    } 
    return true; 
} 

//trigger exception in a "try" block 
try { 
    checkNum(2); 
    //If the exception is thrown, this text will not be shown 
    echo 'If you see this, the number is 1 or below'; 
} 

//catch exception 
catch(Exception $e) { 
    echo 'Message: ' .$e->getMessage(); 
} 
?> 

在上面的例子中,如果条件零异常的鸿沟正在发生,然后它会直接进入catch块,而不是它进入里面if.why?

+2

PHP的内置错误检查不会引发异常。 – Barmar

+0

但我的问题是,是的,我想抓住它,但我不想执行,如果阻塞,如果异常是我在检查除法的行,如果我删除内部的扔,如果然后它不会去抓块它会执行下一个代码,在if语句中仍然有例外。 – pravin

+1

它不执行'if()'块。 '$ number/0'由于除以0而返回'false',所以它不执行'if()'。然后函数返回'true',并打印'如果你看到这个'消息。 – Barmar

您发布的代码不会做你说的那样。

当你执行:

if ($number/0) 

除以零打印警告,然后返回false。由于该值不是真的,它不会进入if块,因此它不会执行throw语句。该函数然后返回true。由于没有抛出异常,执行调用checkNum(2)后的语句,因此它会打印该消息。

当我运行代码,我得到的输出:

Warning: Division by zero in scriptname.php on line 5 
If you see this, the number is 1 or below 

PHP不使用其内置的错误检查异常。它只是显示或记录错误,如果它是一个致命错误,它会停止脚本。

虽然这已在PHP 7中进行了更改。它现在通过抛出Error类型的异常来报告错误。这不是Exception的子类,所以如果您使用catch (Exception $e)则不会被捕获,因此您需要使用catch (Error $e)。见Errors in PHP 7。所以在PHP 7中,你可以写:

<?php 
//create function with an exception 
function checkNum($number) { 
    if($number/0) { 
    throw new Exception("Value must be 1 or below"); 
    } 
    return true; 
} 

//trigger exception in a "try" block 
try { 
    checkNum(2); 
    //If the exception is thrown, this text will not be shown 
    echo 'If you see this, the number is 1 or below'; 
} 

//catch exception 
catch(Error $e) { 
    echo 'Message: ' .$e->getMessage(); 
}