Thanks for link. The reasoning is same as I mentioned above (code duplication). Another reason why finally would be helpful is when a function can choose not to catch an exception (without getting the "Uncaught Exception Error") but yet execute a block of code no matter what, whether an exception is thrown or not (I guess it was mentioned in one of the comments in the link, but I'm not sure). An example about what I mean:
RecordDAO.php
Code: Select all
class RecordDAO {
private $daoFactory;
/**
* @throws PDOException
*/
public function fetchByFilter(stdClass $filter) {
$query = "....";
try {
$this->daoFactory()->query($query);
...
} finally {
$log->debug("Debugging query: \n$query");
}
}
}
BusinessLogicClass.php
Code: Select all
class BusinessLogicClass {
public function processRecords(stdClass $filter) {
$daoFactory = DAOFactory::getInstance();
try {
$data = $daoFactory->getRecordDAO()->fetchByFilter($filter);
//process data here
} catch (PDOException $pdoEx) {
throw new BusinessLogicException($pdoEx);
} finally {
try {
$daoFactory->closeConnection();
} catch (PDOException $ex) {
//you can re throw another exception here or just consume it
}
}
}
}
So instead of catching the exception in every function in DAO class and propogating it to the caller (or worry about handling it), I just catch the one exception in a function in the business logic class (which may also call more DAO class functions), and yet at the same time I can safely log the query in debug mode in my DAO class.
tr0gd0rr wrote:If you are worried about freeing up resources, the normal pattern is to use the `__destruct` magic method. A lot of PHP classes use them to close file handles, sql resources, sql transactions etc. because `__destruct` methods will be called sometime after the Exception, when objects are destroyed.
__destruct() is pretty much like the java.lang.Object.finalize(). But you are putting your faith on when the object gets destroyed (ideally done as soon as when a reference is lost). Plus I don't think objects gets destroyed after an exception is thrown, unless it finally causes the script to terminate (if its an uncaught exception), or the object's scope is local to the function. If a reference to the object exists, it should not be destroyed.
Specifically in dealing with file and sql resources, php will automatically free them up at the end of the script anyway unless there is a segmentation fault which is really rare.
Thats true, but again you are waiting for it to happen.