Wednesday, April 1, 2020

PHP Error and Exception

PHP Error Handling

Error handling is the process of catching errors raised by your program and then taking appropriate action. If you would handle errors properly then it may lead to many unforeseen consequences. It’s very simple in PHP to handle errors. PHP offers a number of ways to handle errors.
 We are going to look at three (3) commonly used methods;

  1. Die statements– the die function combines the echo and exit function in one. It is very useful when we want to output a message and stop the script execution when an error occurs.
  2. Custom error handlers – these are user-defined functions that are called whenever an error occurs.
  3. PHP error reporting – the error message depending on your PHP error reporting settings. This method is very useful in a development environment when you have no idea what caused the error. The information displayed can help you debug your application.

Error Handling Examples

Example-1:
Using die() function: While writing your PHP program you should check all possible error conditions before going ahead and take appropriate action when required. Try the following example without having test.txt file and with this file.

<?php
   if(!file_exists("/tmp/test.txt")) {
      die("File not found");
   }else {
      $file = fopen("/tmp/test.txt","r");
      print "Opend file sucessfully";
   }
   // Test of the code here.
?>

This way you can write efficient code. Using the above technique you can stop your program whenever it errors out and displays a more meaningful and user-friendly message.

Example-2:

<?php   
  $denominator = 0;   
  echo 2 / $denominator;   
?> 

Assuming you saved the file simple_error.php, open the URL 
http://localhost/ simple_error.php
You will get the following results


As you can see from the above results, it makes our application look unprofessional and can be annoying to the user.
We will modify the above code and write an error handler for the application

<?php  
 $denominator = 0;  
 if ($denominator != 0) {  
   echo 2 / $denominator;  
 } else {  
   echo "cannot divide by zero (0)";  
 }  
 ?>

Assuming you saved the above code as error_handling.php, open the URL  http://localhost/error_handling.php


Note: it’s a good security practice displaying a message like the one shown above instead of showing the message like “File not found”.

PHP Exception Handling

An exception is an unexpected program result that can be handled by the program itself. Exception Handling in PHP is almost similar to exception handling in all programming languages.
PHP provides the following specialized keywords for this purpose.
·       try: It represents a block of code in which exception can arise.
·       catch: It represents a 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.
·     finally: It is used in place of catch block or after catch block basically, it is put for cleanup activity in PHP code.

Why Exception Handling in PHP?
Following are the main advantages of exception handling over error handling
·     Separation of error handling code from normal code: In traditional error handling code there is always if-else block to handle errors. These conditions and code to handle errors got mixed so that becomes unreadable. With try Catch block code becomes readable.
·     Grouping of error types: In PHP both basic types and objects can be thrown as an exception. It can create a hierarchy of exception objects, group exceptions in namespaces or classes, categorize them according to types.

Exception handling in PHP: Following code explains the flow of normal try-catch block in PHP:

<?php
// PHP Program to illustrate normal
// try-catch block code

function demo($var) {
    echo " Before try block";
    try {
        echo "\n Inside try block";
             
        // If var is zero then only if will be executed
        if($var == 0)
        {
                 
            // If var is zero then only exception is thrown

            throw new Exception('Number is zero.');
                 
            // This line will never be executed
            echo "\n After throw (It will never be executed)";
        }
    }
         
    // Catch block will be executed only 
    // When Exception has been thrown by try block

    catch(Exception $e) {
            echo "\n Exception Caught", $e->getMessage();
        }
         
        // This line will be executed whether
        // Exception has been thrown or not 
        echo "\n After catch (will be always executed)";
}
 
// Exception will not be raised

demo(5);
 
// Exception will be raised here

demo(0);
?>

Output:

 Before try block
 Inside try block
 After catch (will be always executed)
 Before try block
 Inside try block
 Exception CaughtNumber is zero.

 After catch (will be always executed)



Defining Custom Exceptions

You can even define your own custom exception handlers to treat different types of exceptions in a different way. It allows you to use a separate catch block for each exception type.

You can define a custom exception by extending the Exception class, because Exception is the base class for all exceptions. The custom exception class inherits all the properties and methods from PHP's Exception class. You can also add your custom methods to the custom exception class. Let's check out the following example:
Example:

<?php
// Extending the Exception class
class EmptyEmailException extends Exception {}
class InvalidEmailException extends Exception {}

$email = "someuser@example..com";

try{
    // Throw exception if email is empty
    if($email == ""){
        throw new EmptyEmailException("<p>Please enter your E-mail address!</p>");
    }   
    // Throw exception if email is not valid
    if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {          
        throw new InvalidEmailException("<p><b>$email</b> is not a valid E-mail address!</p>");
    }   
    // Display success message if email is valid
    echo "<p>SUCCESS: Email validation successful.</p>";
} catch(EmptyEmailException $e){
    echo $e->getMessage();
} catch(InvalidEmailException $e){
    echo $e->getMessage();
}
?>
In the above example we've derived two new exception classes: EmptyEmailException, and InvalidEmailException from the Exception base class. Multiple catch blocks are used to display different error messages, depending on the type of exception generated.
Since these custom exception classes inherit the properties and methods from the Exception class, so we can use the Exception class methods like getMessage(), getLine(), getFile(), etc. to retrieve error information from the exception object.
Output: