Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.
class RSS {
public function __construct($uri){
$sXMLObj = $this->getXMLObj();
}
private function getXMLObj(){
//will convert rss fetched data to simple XML object
$this->getRSS();
//throw exception if can't create object
}
private function getRSS(){
file_get_contents($uri);
//throw exception if cant get data from uri
}
}
So what is the "good practice" with exceptions ...
Leave exceptions uncaught and let the developer (that will be using this class) handle them? Is this right?
Errors in XML documents will stop your XML applications.
The W3C XML specification states that a program should stop processing an XML document if it finds an error. The reason is that XML software should small, fast, and compatible.
HTML browsers will display documents with errors (like missing end tags). HTML browsers are big and incompatible because they have a lot of unnecessary code to deal with (and display) HTML errors.
arjan.top wrote:
The question is where to catch exceptions
A couple of other questions, taking the RSS reader as the example: (i) what exception cases do you expect - DNS failures? network timeouts? malformed XML?, (ii) what action do you want to take in response to those exception cases - do you just want to clean things up and display an error message or do you want something more bulletproof with retries and backoffs and alternative servers and cached versions?
If you have a definite error in mind and a definite tactic to respond to that error, it should be a lot clearer where in the call stack to place that error handling. It's not a question of having one place to handle all exceptions.
Just a kind of follow up on dml's post. Some exceptions should be caught and delat with interally if it's clear what should be done and the exception isn't going to be of any help to the user. Other exceptions which provide some descriptive error to the user and on which you cannot make a decision one way or the other, should be left to bubble up. Often this becomes a bit of a grey area and you'll find vastly varying levels of exception use.
Even if the exception message is clear, I think the program should handle the exception and return a response that is appropriate. For RSS maybe something like this:
arjan.top wrote:@arborint:
Interesting approach, but why would I return XML if I can extend Exception class and add error code ec. to it?
Wouldn't it be better?
Because the goal of programs is not to use Exceptions, variables, if statements, etc. -- the goal of programs is to do something useful. And I think you can almost always provide a more useful response than a system error message.