Error Handling
Throw And Catch Exception
try { validateInput(0); } catch (Exception $ex) { echo "Error" . $ex->getMessage(); } function validateInput($input) { if ($input <= 0) { throw new Exception("Invalid input"); } }
Error: Invalid input
Throwing A Custom Exception
set_exception_handler ('exceptionHandler'); // on any exception go to this specific (our custom) method.
throw new Exception("An error occurred"); function exceptionHandler($ex) { echo "Custom Exception Handler: " . $ex->getMessage(); }
Custom Exception Handler: And error occurred
Handling Multiple Exceptions
set_exception_handler ('exceptionHandler'); // on any exception go to this specific (our custom) method.
multipleExceptions(); function multipleExceptions() { try { throw new Exception("Exception - 1"); } catch (Exception $ex) { throw $new Exception("Exception - 2" . $ex->getMessage()); } } function exceptionHandler($ex) { echo "Custom Exception Handler: " . $ex->getMessage(); }
Custom Exception Handler: Exception - 2 Exception - 1
Finally Block
try { throw new Exception("Exception - 1"); } catch (Exception $ex) { throw $new Exception("Exception - 2" . $ex->getMessage()); } finally { echo "finally block executes anyway"; }
finally block excutes anyway
Raise And Handle Error
set_error_handler ('errorHandler'); // on any error go to this specific (our custom) method.
echo (1 / 0); // raise an error
function errorHandler ($errorNumber, $errorMessage) { echo "Custom Error Handler: " . "Error #: " . $errorNumber . " Error Message: " . $errorMessage; }