简体   繁体   English

此PHP中的异常处理?

[英]Exception handling in this PHP?

How can I handle an exception in PHP? 如何处理PHP中的异常? As an example, in the code like this: 例如,在如下代码中:

<?php
   $a=5;
   $b=0
   $c=($a/$b);
   echo $c;
?>

Please help me. 请帮我。

PHP raises warnings and error messages not by throwing an exception, therefore you cannot catch anything here. PHP不会通过引发异常来引发警告和错误消息,因此您无法在此处捕获任何内容。 However, you can modify this behaviour: 但是,您可以修改此行为:

// Register a custom error handler that throws an ErrorException
// whenever a warrning or error occurs
set_error_handler(function ($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});

$a = 5;
$b = 0;

// Now a division by zero will result into an ErrorException being thrown
try {
    $c = $a / $b;
    echo $c;
} catch (ErrorException $e) {
    echo 'Error: ' . $e->getMessage();
}

As far as I'm aware PHP will not throw an exception on division by zero. 据我所知,PHP不会在被零除时抛出异常。 I tested 5.3, it triggers a warning and so would all lesser versions. 我测试了5.3,它会触发警告,所有较小的版本也会触发警告。 So putting that in a try block wont do anything. 因此,将其放在try块中不会做任何事情。 You can map PHP Errors to Exceptions with the ErrorException class, and some screwing around with error and exception handlers. 您可以使用ErrorException类将PHP错误映射到Exceptions,并通过错误和异常处理程序解决一些问题。 See https://github.com/sam-at-github/php_error_exceptions for a reference implementation of that screwing around. 请参阅https://github.com/sam-at-github/php_error_exceptions以获取有关该错误的参考实现。

First: you are doing a division at the second line code (which can be devision by zero). 首先:您正在对第二行代码进行除法(可以除以零)。

Second: no need to return false in your method since you are throwing an error. 第二:由于抛出错误,因此无需在方法中返回false。

Third: Why using an exception here and not just let you method return true of false and check on that before executing the devision. 第三:为什么在这里使用异常,而不仅仅是让您的方法返回true到false并在执行分区之前对其进行检查。

Fourth: Why having a method if you only need to check on the value of $y. 第四:如果只需要检查$ y的值,为什么要有一个方法。 Calling the method or including an if-statement requires both just one line of code. 调用该方法或包含if语句仅需要一行代码。

So, why can't it just be like: 所以,为什么不能这样:

case '/':                  
    if($b > 0)
        $prod = $a / $b;
    break; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM