Catching Exceptions Syntax Error in PHP
-
21-09-2019 - |
Question
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.');}
}
Solution
OTHER TIPS
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.');}
}
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.
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.