tags:

views:

130

answers:

4

Possible Duplicate:
What is the advantage of using try {} catch {} versus if {} else {}

I'd like to know whether, generally speaking, it's better to use a try/catch construct or to try to prevent this exception by (excessive?) use of if/else. Example: should I catch a FileNotFoundException, or should I test and try to find the file first.

What would be the best approach?

+10  A: 

They are totally different. They are not interchangeable, and which is appropriate is determined by the requirement and context.

EDIT: This answer is based on the original, unedited question. The original, in it's entirety was:

PHP : if/else vs try/catch

which is better

Scott Saunders
Actually, that depends on your point-of-view and the interpretation of the "question". Many textbooks suggest if/else as an alternative to try/catch: i.e., prevent the error, don't catch exceptions unless you really need to and are capable of recovering state and let real exceptions fire.
Abel
+2  A: 

They have different purposes. It depends on the context. There is no better.

I suggest you read about Exceptions and the if-else statement.

Felix Kling
They have different purposes indeed, but try/catch is often a warning for code-smell and should be rewritten as if/else instead to correct program flow and allow input to be filtered. Most exceptions should be thrown, not caught and signify that input or conditions are beyond what was expected.
Abel
@Abel: As I said, it depends on the context. Generally speaking you cannot say that one is *better* than the other.
Felix Kling
A: 

I think you don't really understand what's if/else and try/catch.

KahWee Teng
+2  A: 

Rule of thumb: don't use try/catch for controlling program flow, just use it to catch errors.

zwip
okay i get it thanks
Web Developer