c# - PHP 异常处理与 C#

标签 c# php error-handling

这是一个非常基本的问题(我希望如此)。我完成的大部分异常处理都是使用 c# 完成的。在 c# 中,任何在 try catch block 中出错的代码都由 catch 代码处理。例如

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 语句吗? 如果(除以零)抛出错误 请告诉我,我不必用 throw 预测 try catch 中的每一个可能的错误。如果我这样做,有没有办法让 php 的错误处理表现得更像 c#?

最佳答案

您还可以使用 set_error_handler() 转换所有 php 错误和 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();
}

关于c# - PHP 异常处理与 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4020016/

相关文章:

c# - TFS 2012 插件在保存多个工作项时缺少事件?

C# - 全局程序对象

php - 防止 php 类被扩展

codeigniter - 自定义错误,例如,使用Codeigniter方法时,超过1条记录

c# - 使用ZOHO SMTP配置发送邮件时出现`The operation has timed out.`异常

c# - 无论如何在 C# 中获取所有文件名而没有异常(exception)?

php - 为事件源网站存储和检索用户列表的有效方法

php - sql查询多个or条件-哪一个匹配

go - 从 PathError 中获取 errno 值的正确方法

error-handling - 房间迁移失败,没有错误