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 exception
function verify($digit) {
if($digit>1) {
throw new Exception("Parameter should be less than 1");
}
return true;
}
//check for exception
try {
verify(2);
//this text will display if there is no exception
echo 'You passed a value lower than 1';
}
//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
?>

Explanation

  • Line 5: We use the throw to define a new Exception when the number passed into the verify function is greater than 1.
  • Line 11:We start the try block.
  • Line 12: We call the verify function and pass 2 as a parameter.
  • Line 14: We 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.
  • Line 18–20: We catch the exception and display the message defined in the throw in line 5.

Free Resources