PHP web应用程序何时使用try / catch [英] PHP web application when to use try/catch

查看:135
本文介绍了PHP web应用程序何时使用try / catch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用PHP与CodeIgniter框架。我读了一些文章,说明使用try / catch方法是在坏的做法。

I am using PHP with CodeIgniter framework. I read some articles that stating using try/catch methods is in bad practice.

我理解在开发中使用日志时,可能发生的潜在错误,让实际的错误然后使用 log_message('level','message')

I understand to use logging in development when a potential error can occur and let the actual error happen then log it using log_message('level', 'message')

记录。并处理出现的任何错误。我应该使用try / catch块,例如像...等。

But when in deployment you want to suppress and handle any errors that arise. Should I be using try/catch blocks, for instance in something like...

try { 
    $this->data['important'] = $this->Test_Model->do_something($data);
    if(empty(data['important'])) {
    throw new Exception('no data returned');
}

catch (Exception $e) {
    //alert the user then kill the process
    var_dump($e->getMessage());
}



当我使用正确的try / catch时,我很困惑。 p>

I'm confused when I use be using try/catch correctly.

推荐答案

代码中有语法错误,应该是:

There's a syntax error in your code, it should be:

try { 
  $this->data['important'] = $this->Test_Model->do_something($data);
  if(empty(data['important'])) {
    throw new Exception('no data returned');
  }
} catch (Exception $e) {
  //alert the user.
  var_dump($e->getMessage());
}

使用 try / catch 不是一个坏习惯。

异常是可以捕获的,无需覆盖PHP默认错误处理程序。这意味着您可以在运行时发生异常时执行某些操作。

Exceptions are catch-able without needing to override PHP default error handler. This means that you can do something when exceptions occurs in run-time.

日志是适合您的。如果您的应用程序不健康,并且您记录了可能存在的问题点,您可以更容易地识别错误。您的日志和本机日志之间的主要区别是上下文,本机日志没有上下文,他们只有事件和可能的堆栈跟踪。

Logs are for you. If your application isn't healthy and you logged possible problematic points, you can identify errors more easily. The main difference between your log and native log is the context, native log doesn't have context, they have just the occurrence and possibly stack trace.

这篇关于PHP web应用程序何时使用try / catch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆