views:

185

answers:

4

I'm trying to use exceptions in PHP as a way of avoiding multiple if-then-else blocks. However, when I try to catch the exception, I get the error Parse error: syntax error, unexpected T_CATCH in /directory/functions.php on line 66. Am I doing something wrong with my throwing and catching?

function doThis($sSchool, $sDivision, $sClass, $sUsername, $sCode,$query1,$query2) 
    {
     connectDb();
     global $dbConnection;

     $sDivisionIdArray = mysqli_query($dbConnection,$query1);
     if ($sDivisionIdArray==false){throw new Exception ();}


     $sDisplayQueryArray = mysqli_query($dbConnection,$query2);
     if ($sDisplayQueryArray==false){throw new Exception ();}

    catch (Exception $e) // This is line 666
     {echo ('Sorry, an error was encountered.');}
    }
+3  A: 

You forgot the try statement.

function doThis($sSchool, $sDivision, $sClass, $sUsername, $sCode,$query1,$query2) 
{
    try
    {
       connectDb();
       global $dbConnection;

       $sDivisionIdArray = mysqli_query($dbConnection,$query1);
        if ($sDivisionIdArray==false){throw new Exception ();}


       $sDisplayQueryArray = mysqli_query($dbConnection,$query2);
       if ($sDisplayQueryArray==false){throw new Exception ();}
    }
    catch (Exception $e) // This is line 666
    {echo ('Sorry, an error was encountered.');}
}
Dinu Florin
+2  A: 

You can't use catch without a try.

Sarfraz
A: 

To increase your knowledge of PHP exceptions, you may also pass messages in your thrown exceptions which can be caught and stored (if you so choose).

function doThis($sSchool, $sDivision, $sClass, $sUsername, $sCode,$query1,$query2) 
{
    try
    {
       connectDb();
       global $dbConnection;

       $sDivisionIdArray = mysqli_query($dbConnection,$query1);
       if ($sDivisionIdArray == false)
           throw new Exception ('Query 1 failed');


       $sDisplayQueryArray = mysqli_query($dbConnection,$query2);
       if ($sDisplayQueryArray == false)
           throw new Exception('Query 2 failed');
    } catch (Exception $e) {
        echo ($e->getMessage());
    }
}

If you fail to include try/catch blocks around a thrown exception, you could choose to include a default exception handler in your code which will catch all exceptions thrown using set_exception_handler. This can be used to standardize a 404/500 error page and also to handle errors appropriately and possible log them to a file.

cballou
A: 

Other answers have pointed out the lack of a try block. I just wanted to mention that using exceptions for flow control isn't always a great idea. Aside from the conceptual issue (exceptions should signal that something out of the ordinary happened which must be dealt with, not serve as a glorified goto), use of exceptions may be less efficient.

EloquentGeek