8

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.

Community
  • 1
  • 1
Edward
  • 3,061
  • 6
  • 32
  • 52
  • There are multiple cases when you don't want to suppress exceptions. This is a very interesting exceptions classification by Eric Lippert http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx. – Nikolai Samteladze Dec 18 '13 at 23:36
  • Throwing an exception in the same code block as handling it, is bad practice. Exceptions are super useful for separating components though. `FormBuilder` throws an exception, `Action` handles it. `EmailValidation` throws an exception, `UserModel` handles it. Etc. #IMHO – Rudie Dec 18 '13 at 23:38
  • Also, exceptions are very useful when your method does not know what to do with the problem, but some the method that called yours might. E.g. if you could not get some data from API, it will be appropriate to throw an exception and let the calling method to decide what to do (e.g. fail or make another call). – Nikolai Samteladze Dec 18 '13 at 23:38
  • 1
    http://stackoverflow.com/questions/5199146/when-to-use-try-catch-blocks?rq=1 more details here – Nikolai Samteladze Dec 18 '13 at 23:39
  • @Rudie can you suggest a good example/tutorial of a bubble up exception handler for php? – Edward Dec 19 '13 at 00:06
  • @Edward No, I don't know any, sorry. – Rudie Dec 19 '13 at 17:32

2 Answers2

20

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

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

Using try/catch isn't a bad practice.

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.

usersn
  • 127
  • 1
  • 14
Andrey
  • 1,476
  • 1
  • 11
  • 17
1

Exceptions should only be caught in two cases:

  1. When the exception itself does not require an immediate halt to your program's execution, ie: the catch block intelligently handles the exception and allows program execution following the block to happen in a sane manner.
  2. When you want to perform additional error handling and shut down cleanly, and/or log/display error information. Optionally, the exception can then be re-thrown the exception to "bubble up" in the stack so other routines can do the same. eg:

    try {
      //code
    } catch( Exception $e ) {
      echo "friendly error message";
      logging_function($e->getMessage());
      throw $e;
    }
    

The most widely-abused method is to simply use a try/catch block to silently ignore exceptions and continue execution as if everything was still OK. Doing something like this will come back and bite you in the ass when something goes wrong much later in your program's execution, that that ignored exception would have warned you about, which you then spend hours of your life tracking back to:

try {
  // code
} catch( Exception $e ) { /* L7: Exception handling is for squares! */ }

In these cases it's much better to let the Exception raise an error where it happened instead of where ignoring that error caused a worse one.

Sammitch
  • 30,782
  • 7
  • 50
  • 77