I have a simple try/catch. If an error is thrown I want a function to run but the page should continue running.
I am noticing, that the function isn't running. If I put a die() after my function , then the function runs, but my page stops.
Am I doing something wrong?
try {
$stmt->execute();
}
catch(Exception $e) {
sendError($e );
die( 'Error'); //neccesary or function doesn't run
}
die( 'Error');
is not necessary for the function to run. It would help if you show us the sendError()
function and what it does. You must understand that the function is only called when an Exception is thrown and caught. So, it does not appear that you are doing anything wrong.
It will depends as to the rest of the code and the environment around the try/catch block, and possibly the version of PHP.
For example this code:
<?php
namespace tests;
try {
throw new Exception();
} catch (Exception $e) {
echo "caught exception";
}
echo "end";
Will not print the 'caught' message, or 'end'. On PHP 7.2, with all errors & warnings being caught and displayed, it's a fatal error:
PHP Fatal error: Uncaught Error: Class 'tests\Exception' not found in test.php:5
In PHP 5.6, Fatal error: Class 'tests\Exception' not found
.
In this instance, it is because I am are not namespacing the Exception
, and so it is trying, and failing to use a local version.
If the code also has ini_set('display_errors', false);
before the try
, then the script will not show anything - at all.
So -make sure that Exception
is properly namespaced, with use Exception;
at the top, or in place, with } catch (\Exception $e) {
.