我应该在这里使用例外吗?

时间:2012-04-04 16:49:07

标签: php exception exception-handling

我是异常的新手,并试图找出何时适合使用它们。在下面的PHP代码中,我想更改echo(无需告诉用户)只需记录消息。我应该将echo替换为log->notice(...)(例如),还是应该使用异常(我打算记录该异常)。

if (file_exists($file)) {
    echo 'File already exists and will be overwritten.';
}

另外,如果我应该使用异常,那么在这种情况下如何正确使用?

3 个答案:

答案 0 :(得分:1)

异常通常用于处理意外行为 - 例如错误或问题。

对于上面的示例,我认为不需要它,因为您可能希望文件存在,并且如果已经存在文件,应该以一种流式编写程序(就像您一样)完成了)。这一切都取决于你期望发生的事情,而不是。

正常使用的情况可能是:

try
{
    some_function();
}
catch (Exception $e)
{
    echo 'Function didn\'t behave as expected, please try again, here is the error: '.$e->getMessage();
}

答案 1 :(得分:1)

异常是处理错误的标准方法..但它们可能是您需要使用异常的一些情况。

如果您只想验证文件..不需要例外..如果错误的输出需要您重定向或有连锁反应或者您正在开发框架等...我会建议您使用Exception < / p>

try
{
    if (file_exists($file)) {
           throw new Exception('File already exists and will be overwritten.');
    }
}
catch (Exception $e)
{
   header("Location: error?msg=". base64_encode($e->getMessage()));
}

结论

您使用该脚本将决定是否更好地使用异常

我跳这个帮助

由于

:)

答案 2 :(得分:1)

异常是为了在遇到错误时中断执行流程。这一切都取决于你如何构造流,如果你想停止流,因为文件存在,你可以执行以下操作:

try {
    if (file_exists($file)) {
        throw new Exception(sprintf('File already exists and will be overwritten';
    }

    // If above conditional is realized, no code from this point forward will be
    //  executed

} catch (Exception $e) {
    error_log($e->getMessage());
}

在您的具体示例中,我认为保持代码原样是可以的,因为它似乎只是一个警告,这意味着您不想打破执行流程,而是在警告之后继续执行代码

如果你真的想要使用异常,你可以实现嵌套异常,但它会变得复杂并最终成为过度杀伤。

通过PHP文档了解exceptions的更多信息。

  

我应该用log-&gt; notice(...)

替换echo

我愿意,除非你希望用户知道这个问题。

相关问题