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

Tags: php mysql pdo
By : jeroen
Source: Stackoverflow.com
Question!

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.)?

By : jeroen


Answers

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).


Multi query,

Batching.

And most importantly: Hooks to supplement/override whatevery functionality that works in ways you did not expect/want/feel like that day.

The last part is one place where NHibernate excels.



Some kind of query interface (like linq or Criteria)

Some kind of mapping functionallity

Support for transactions and Unit of work

By : Jon


This video can help you solving your question :)
By: admin