views:

71

answers:

3

I've been developing big applications using try/catch to handle all the exceptions and errors; however, I've been trying to figure out: When is it correct to use a try/catch statement?

Is there a good practice/rule for try/catchs?

Currently I'm building a SEO library for my PHP Framework and I have a "small" function, and I asked myself "Should I really use try/catch on this small function?"

If someone can guide me in this matter I would be really thankful.

A: 

Try/Catch is the most useful when either you have your own error handling function (which you should), or also when you want to suppress errors. You should never resort to using PHP's built-in @ error suppressing, so using try/catches can record the errors using your error function and help you suppress them in a helpful way.

That's when I personally use them. If you're using them in the rest of your framework, I'd continue using it for consistency (especially if you're using a custom error handling function - that'll really help with the continuity and consistency of the app).

BraedenP
A: 

using it if you're using that kind of coding standard. Using both exceptions and return codes can turn into a convoluted mess and slow development (trying to remember how to handle errors for each function). Maybe you don't need a try/catch block in your tiny functions -- but if you structure the script right, you can just throw exceptions from your small functions and have the larger controlling functions calling them in a try block.

However, I have read that just using exceptions can easily turn into a convoluted mess as well. Your scripts have to be pretty logically consistent to use them most effectively.

Carson Myers
A: 

If nothing inside of your small function has the ability to throw an exception, there isn't really a point to wrapping it in a try/catch block. If it truly is a small function, perhaps it would be okay to have a try/catch handle the block of code that calls your small function (in addition to other code). You want to take care to not end up blanketing your code with too high of level of try/catches that don't really tell you what the specific problem was/where it happened.

Adam