tags:

views:

1887

answers:

10

I am switching from plain mysql in php to PDO and I have noticed that the common way to test for errors is using a try / catch combination instead of if / else combinations.

What is the advantage of that method, can I use one try / catch block instead of several nested if / else blocks to handle all errors for the different steps (connect, prepare, execute, etc.)?

+4  A: 

In general, try-catch blocks are great because they will break (move to the catch statement) whenever the exception occurs. If-else blocks rely on you predicting when the error will happen.

Edit: Also, catch blocks won't stop your code from halting when an error is hit.

Perchik
Good point (catch won't stop code from halting when an error is hit, especially if you handle a narrow exception type)
Jared Updike
+5  A: 

That’s exactly the advantage, using one try/catch instead of multiple if statements. You will also be able to catch any unanticipated errors.

Shaun Humphries
+2  A: 

Since PDO is using objects, they are raising Exceptions if an error occur. The old mysql/mysqli were mere functions and didn't throw Exceptions they simply returned error codes. Try/catch is used when an Exception can be thrown from the code, and you catch it in the catch-clause, which is an object oriented way to handle errors. You can't catch Exceptions with if/else blocks - they share nothing with try/catch.

Björn
The Mysqli extension exposed both a functional and OO API.
Alan Storm
+1  A: 

Try/Catch totally separates the error handling logic from the object business logic.

Trap
+1  A: 

@Perchik:

My general philosophy of error handling:

You should use if / else to handle all cases you expect. You should not use try {} catch {} to handle everything (in most cases) because a useful Exception could be raised and you can learn about the presence of a bug from it. You should use try {} catch {} in situations where you suspect something can/will go wrong and you don't want it to bring down the whole system, like network timeout/file system access problems, files doesn't exist, etc.

Vexing exceptions

Jared Updike
Well right, I agree with you. Perhaps I oversimplified. Try-catch should only be used when something might go wrong and you don't want it to kill your program.
Perchik
+2  A: 

Throwing and catching an exception is an expensive operation compared with most any other primitive operation. If this is a piece of code that needs to perform well (eg, in a tight loop), you will want to look at your use case - if you expect the exceptions to be thrown relatively often, you will be better off with an if/else perforance-wise (unless the underlying code is just wrapping an exception for you, in which case there's no gain at all). If the exceptions are only thrown in rare circumstances, then you're better off with a try/catch to avoid the overhead of branching in a tight loop.

Not Sure
+8  A: 

I'd use the try/catch block when the normal path through the code should proceed without error unless there are truly some exceptional conditions -- like the server being down, your credentials being expired or incorrect. I wouldn't necessarily use it to handle non-exceptional errors -- say like the current user not being in the correct role. That is, when you can reasonably expect and handle an error that is not an exceptional condition, I think you should do your checks.

In the case that you've described -- setting up and performing a query, a try/catch block is an excellent way to handle it as you normally expect the query to succeed. On the other hand, you'll probably want to check that the contents of result are what you expect with control flow logic rather than just attempting to use data that may not be valid for your purpose.

One thing that you want to look out for is sloppy use of try/catch. Try/catch shouldn't be used to protect yourself from bad programming -- the "I don't know what will happen if I do this so I'm going to wrap it in a try/catch and hope for the best" kind of programming. Typically you'll want to restrict the kinds of exceptions you catch to those that are not related to the code itself (server down, bad credentials, etc.) so that you can find and fix errors that are code related (null pointers, etc.).

tvanfosson
Thanks a lot! Out of curiosity, how would you handle / qualify a query that results in an empty row when you expect data (for example when someone manually changes a number in a query string)?
jeroen
Depends on the exact circumstance, but if it's possible that the query will return no data I'd simply check if there was data (row count != 0) and render a "query returned no results" message instead.
tvanfosson
+2  A: 

The advantage of try/catch, and exceptions in general, is more for the people developing libraries like PDO. They allow a system developer to handle undefined situations or unexpected results in a quick and easy way. Take a database connection. What should a system do if the database can't be reached. Should it halt execution? Try again? Throw a warning and continue? The system developer can't know what you'll need it to do, they they throw an exception, which you'll later catch and handle.

The advantage for you, as a consumer of the system is rather than getting some vague error code back, or a simple boolean false that it failed, you get an Exception object which will

  1. Be named in such a way that it's more obvious what went wrong (If I remember right, PDO only has one Exception type, but other systems contain multiple exception types for different kinds of errors)

  2. May/should contain methods and properties which can help you figure out why the exception was thrown

That's the theory anyway. There are lots of smart people who claim Exceptions are the way to go. There are also lots of smart people who think Exceptions are the devil, and a crutch for lazy system developers. There is nothing resembling consensus on this issue.

Alan Storm
A: 

Completely agree with @Jared Updike

Usually exception handling is done with the user knowing little or nothing about it. On the other hand, the user of the system knows about what happens inside an if-else block.

eg. It should be an "else" clause that shows an ATM user, the message "Insufficient bank balance" when his balance is low. And this message CANNOT be sitting inside a "catch" block for any reason !!

Vijay Dev
A: 

Everybody else had good answers - but I figured I would throw my own in:

  1. Try/Catch is an actual exception handling mechanism - so if you change your exceptions, it will automatically work on all try/catch statements.
  2. Try/Catch gives the opportunity to run code even in the case of a major exception that might kill the if/else and in addition, the try statement can be rolled back (if you're savvy).
Adam Nelson