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.
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.
Exceptions should only be caught in two cases:
- 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.
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.