In PHP, an exception can be seen as discontinuation in the normal flow of program execution. An exception can also be seen as an error that causes a complete disruption in the code execution flow.
Exception handling is making the program respond appropriately when an error occurs. If an error occurs, the program should respond with the actual cause of the error and possibly where the error occurred. We achieve this functionality using the try-catch
exception handler.
(try(//protected code)(catch Exception e1 (//catch block)))
The try-catch
checks for errors in a code (protected code
) and output specific error messages (catch block
) when an error arises in the code block.
<?php//create function with an exceptionfunction verify($digit) {if($digit>1) {throw new Exception("Parameter should be less than 1");}return true;}//check for exceptiontry {verify(2);//this text will display if there is no exceptionecho 'You passed a value lower than 1';}//catch exceptioncatch(Exception $e) {echo 'Message: ' .$e->getMessage();}?>
throw
to define a new Exception
when the number passed into the verify
function is greater than 1
.try
block.verify
function and pass 2
as a parameter.echo
message if the function runs successfully if the function throw
an exception the message won't display, instead the catch
block will catch this exception and output the defined exception created in line 5.catch
the exception and display the message defined in the throw
in line 5.