Question regarding exceptions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Question regarding exceptions

Post by social_experiment »

If you have the following code as part of a function that creates the connection to a database server :

Code: Select all

<?php
if (!$connect) throw new Exception('Cannot connect');
else {
 if (!$select_db) throw new Exception('Cannot select database');
}	
?>
and the following code as part of a function that processeses a mysql query :

Code: Select all

<?php
if (!$sql) throw new Exception('Error with query');
?>
would the following code sample, to catch the exceptions; if any, be correct?

Code: Select all

<?php
try {
 //code that executes query
}
catch (Exception $e) {
 echo $e->getMessage();
} ?>
If there are 2 or 3 exceptions that can be caught, will the code above be correct or do i have to try and catch another exception (inside the first try statement)?
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
User avatar
Jade
Forum Regular
Posts: 908
Joined: Sun Dec 29, 2002 5:40 pm
Location: VA

Re: Question regarding exceptions

Post by Jade »

Post Reply