What is Exception Handling in PHP ?

Exception handling in php  is used to modify the normal flow of code execution if a specified error occurs. When an exception is given , the following  code will not be executed, and PHP will try to find the appropriate “catch” block. If an exception is not caught, a fatal error will be displayed.

Keywords in Exception Handling:

  • try : This is a block of code where an exception may occur.
  • catch: It represent block of code that will be executed when a particular exception has been thrown.
  • throw: It is used to throw an exception. It is also used to list the exceptions that a function throws, but doesn’t handle itself. Each “throw” must have at least one “catch”.
  • finally: It is used in place of catch block or after catch block basically it is put for cleanup activity in PHP code.

Example :

<?php
function checkMarkStatus($mark) {
  if($mark>=5) {
    throw new Exception("The Student is Pass.");
  }
  return true;
}
try {
  checkMarkStatus(5);
  echo 'The Student is Fail';
}
catch(Exception $e) {
  echo $e->getMessage();
}
?>

Advantages of Exception Handling :

  • Sometimes error handling is very difficult for the developer to understand in normal coding. With try catch block it is more readable and understandable.
  • Exceptions allow you to distinguish between different types of errors, and is also great for routing.
  • The thrown exception can then be handled by a custom error handler.