It makes exception handling a lot cleaner. Firstly it's much simpler to bubble errors up through your classes, for example:
class a {
function methodA() {
throw new Exception('The Error');
}
}
class b {
function methodB() {
$a=new a();
$a->methodA();
}
}
$b=new b();
try {
$b->methodB();
} catch(Exception $e) {
echo($e);
}
Notice that the exception is not caught and then re-thrown in class b, it is allowed to bubble up and is then only cought at when the error is going to cause an issue.
This kind of exception handling really starts to shine when you start using (and creating) different Exception types for different errors. For example:
Assume that the exception classes are already written. Also, this example is quite OTT, you wouldn't need all those different exceptions for such a simple task.
function writeToFile($file, $data) {
if(!file_exists($file)) throw new FileNotFoundException();
if(!is_writable($file)) throw new FileNotWritableException();
if(empty($data)) throw new EmptyDataException();
if(!$fp=fopen($file, 'w')) throw new FailedOpenException();
if(!fwrite($fp, $data)) throw new FailedWriteException();
return true;
}
try {
writeToFile($file, $data);
} catch(FileNotFoundException $e) {
//handle exception
} catch(FileNotWritableException $e) {
//handle exception
} catch(EmptyDataException $e) {
//handle exception
} catch(FailedOpenException $e) {
//handle exception
} catch(FailedWriteException $e) {
//handle exception
}
See? You can apply differnt code depending on the nature of the exception. Some may be recoverable from, others may be fatal.