What is the try throw and catch in PHP?
Overview
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.
Syntax
(try(//protected code)(catch Exception e1 (//catch block)))
Try and catch syntax
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.
Example
<?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();}?>
Explanation
- Line 5: We use the
throwto define anew Exceptionwhen the number passed into theverifyfunction is greater than1. - Line 11:We start the
tryblock. - Line 12: We call the
verifyfunction and pass2as a parameter. - Line 14: We
echomessage if the function runs successfully if the functionthrowan exception the message won't display, instead thecatchblock will catch this exception and output the defined exception created in line 5. - Line 18–20: We
catchthe exception and display the message defined in thethrowin line 5.