The magic __toString() method will be invoked automatically when the code enters the catch()statement and the custom exception message will be printed code example
Example: try catch in php
Try catch comes under exception handeling concept where using this we control the runtime error and modify the message as we want.
function checkdata($number){
if($number > 10){
throw new Exception("Number is greater than 10");
}
return true;
}
try{
checkdata(15);
echo "The number is below 10";
}
catch(Exception $e){
echo "Message :".$e->getMessage();
}
In above code if condition is not satisfied then it will throw exception and which gets caught by catch block and show the error message.