PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
I've recently decided to consider throwing Exceptions for errors but fail to see the benefit. Below are two sets of code (the class not included because it's not really relevant), and I'd appreciate any feedback regarding whether or not I am using Exceptions correct and, if so, how it trumps traditional error handling:
<?php
$connection = MySQLConnection::setConnection('******', '******', '******'));
if (!$connection->isConnected()) {
echo 'Unable to connect to the server';
}
elseif (!$connection->setDatabase('database')) {
echo 'Unable to select the database';
}
?>
The main difference is that an exception communicates the error through multiple call levels. With return values you are responsible for bubbling the error back up the call stack. So in your example, using an exception may simplify the code within the MySQLConnection if the error occurs within a composited object, or in this code if the error needs to be handled somewhere other than immediately after the call.
I think what many people new to exceptions do wrong, is to always use try-catch blocks. That is unnecessary when you're only going to echo getMessage(). You could create a custom exception handler via set_exception_handler() and handle them in such cases. If you are going to do something else when an exception is thrown, it absolutely OK to use a try-catch. In these examples, I think it is best to just throw them without catching them and let an exception handler do something with them instead.
Hanse wrote:I think what many people new to exceptions do wrong, is to always use try-catch blocks. That is unnecessary when you're only going to echo getMessage(). You could create a custom exception handler via set_exception_handler() and handle them in such cases. If you are going to do something else when an exception is thrown, it absolutely OK to use a try-catch. In these examples, I think it is best to just throw them without catching them and let an exception handler do something with them instead.
An exception handler is a last resort. You can't recover from a problem by catching an exception that late.
Since exceptions are akin to errors, isn't what you're suggesting to not do error checking?
I don't see no reason to catch the exception just to tell the user something went wrong. If you want to do something special when the error occurs (f.ex. rolling back a transaction) it is beneficial, but if it is just to show the message, I'd rather create a super awesome exception handler used in development mode with all info for debugging and a simple one in production. Maybe this is bad, though.