douluoyou9876 2010-10-26 01:14
浏览 38
已采纳

PHP异常处理与C#

this is a really basic question (I hope). Most of the exception handling I have done has been with c#. In c# any code that errors out in a try catch block is dealt with by the catch code. For example

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

The error would be displayed in errorCode.text. If I were to try and run the same code in php however:

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

The catch code is not run. Based on my limeted understanding, php needs a throw. Doesn't that defeat the entire purpose of error checking? Doesn't this reduce a try catch to an if then statement? if(dividing by zero)throw error Please tell me that I don't have to anticipate every possible error in a try catch with a throw. If I do, is there anyway to make php's error handling behave more like c#?

  • 写回答

4条回答 默认 最新

  • douhunkuang8955 2010-10-26 01:23
    关注

    You could also convert all your php errors with set_error_handler() and ErrorException into exceptions:

    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();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Java中消息和缓存如何使用
  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路