3 days ago I started rewriting one of my scripts in OOP using classes as a practice after reading a lot about the advantages of using OOP.
Now I\'m confused weather I sh
Your question is not uncommon, whether/when to use exception is sometimes a philosophical decision and many experienced developers can't wrap their heads around it.
That being said, I've found that listing out the distinct properties of each way of handling error makes it easy to choose your preferred way:
0
mean success or failure?)When to use: It's pretty obvious. Use return codes when you trust the caller (internal code or trivial errors which can be safely ignored).
try/catch
)When to use: When you don't trust your caller as much (third party) or you really need to make sure your error code doesn't go ignored.
When to use: It's usually obvious enough. You need everything to stop immediately.
(In a PHP context, I don't think it makes much difference. The above suggestions should still apply.)
(Aside)
Usually it's tempting to just write out an error message when something bad happens (especially when the first programming language you learned is PHP :P). But if you really want to grok OOP, it's not a proper way to handle errors.
Every object or every function should ideally only perform one function. If one function writes error to the screen and does its own thing, it's difficult to later switch to a DatabaseErrorLogger
or TextFileErrorLogger
or etc. One approach would be to supply a logger to use (this is called Dependency Injection). Another way to do it is to use exception -- this way, the caller gets to choose which ErrorLogger
to use.