Edward Edward - 5 months ago 53
PHP Question

PHP web application when to use try/catch

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

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')


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());
}


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

Answer

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 then kill the process
  var_dump($e->getMessage());
}

Using try/catch isn't a bad pratice.

Exceptions are catchable without needing to override PHP default error handler. This means that you can do something when exceptions occurs in runtime.

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.