代码之家  ›  专栏  ›  技术社区  ›  CountMurphy

PHP异常处理vs C#

  •  3
  • CountMurphy  · 技术社区  · 15 年前

    try
    {
     int divByZero=45/0;
    }
    catch(Exception ex)
    {
     errorCode.text=ex.message();
    }
    

    错误将显示在errorCode.text中。但是,如果我尝试在php中运行相同的代码:

    try{
        $divByZero=45/0;
        }
    catch(Exception ex)
    {
      echo ex->getMessage();
    }
    

    捕获代码未运行。基于我有限的理解,php需要一次尝试。这难道不违背错误检查的全部目的吗?这难道不将try-catch减少到if-then语句吗? if(除以零)抛出错误 请告诉我,我不必在一次投球尝试接球中预料到每一个可能的错误。如果我这样做了,还有什么能让php的错误处理行为更像c#?

    4 回复  |  直到 15 年前
        1
  •  6
  •   zerkms    15 年前

    您还可以使用 set_error_handler() ErrorException 例外情况:

    function exception_error_handler($errno, $errstr, $errfile, $errline )
    {
        throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
    }
    set_error_handler("exception_error_handler");
    
    try {
        $a = 1 / 0;
    } catch (ErrorException $e) {
        echo $e->getMessage();
    }
    
        2
  •  2
  •   William Linton    15 年前

    PHP的try-catch是在该语言的后期实现的,因此它只适用于用户定义的异常。

    错误 set your own error handler .

    定义和捕捉 例外情况 :

    function oops($a)
    {
        if (!$a) {
            throw new Exception('empty variable');
        }
        return "oops, $a";
    }
    
    try {
        print oops($b);
    } catch (Exception $e) {
        print "Error occurred: " . $e->getMessage();
    }
    
        3
  •  2
  •   Phil    15 年前

    http://php.net/manual/en/language.exceptions.php

    “内部PHP函数主要使用错误报告,只有现代的面向对象扩展使用异常。但是,错误可以简单地转换为异常和ErrorException。”

    另见 http://www.php.net/manual/en/class.errorexception.php

        4
  •  1
  •   Tomas Petricek    15 年前

    我认为用PHP处理这个问题的唯一方法是编写:

    try
    { 
      if ($b == 0) throw new Exception('Division by zero.');
      $divByZero = $a / $b; 
    } 
    catch(Exception ex) 
    { 
      echo ex->getMessage(); 
    }