9780183527 [email protected]
Exception Handling in PHP

Exception Handling in PHP

Exception Handling in PHP is the process followed by the programmer to handle exceptions which are thrown during the program execution. Exceptions are raised when some line of code breaks and does not execute as expected. These exceptions if not caught properly will cause our application to stop which will not be a good experience for end users who are not aware of the underlying details of the application. A good programmer always write his code considering exception handling in mind.

Difference between Errors and Exceptions in PHP

  • Errors in PHP are those exceptions which cannot be handled and leads to halting of the application.
  • Errors are generally raised by the environment in which the application is running. For ex. if the memory runs out of space.
  • Errors can not be handled using try catch block.

Handling Exceptions using Try Catch Block

Exceptions in PHP are handled using try catch block in which the code where there is a possibility of the exception being raised is put into try block and the exception handling code is placed in catch block which if followed by try block.

For example:

// code before try block

try {
  // code to be executed
 
  // Something unexpected happens the the control of execution will jump to catch part
 
  // once the control is transferred to catch part the rest of the code in try block will not be executed
} catch (Exception $e) {
  // exception will be handled here
  // $e->getMessage() contains the error message
  // Exception logging can be used with the method name in which the exception has occured along with the excetion detail
}
 
// code after try block

Inside the catch block an exception object is passed which consists of the information about the exception.

Throwing an exception using throw keyword

We can also explicitly throw exceptions using the throw keyword. For example we can validate the data entered by the user and can throw exception is the data is not valid.

For example:

<?php
try {
    // store the file path in a variable
 
    $file_path = "config.php";
 
    if (!file_exists($file_path))
    {
      throw new Exception("file not found.");
    }
} catch (Exception $e) {
    echo $e->getMessage();
    die();
}
?>

In the above example we are checking whether a config.php file exists or not if it does not exist we are throwing an exception manually which will be caught in the catch block where we are showing the error message and also stopped the execution of the application.

Try block can not stand alone it must be followed by at least one catch block. Catch blocks can also be more than one if we want to handle multiple exception types where more specific exceptions are always kept at the top and more general exception classes are kept at the bottom.

Exceptions if they are not handled in the same function in which they are thrown will be propagated further to the calling code where they can be handled.

For example:

<?php  
//function with an exception  
function checkNumber($num) {  
   if($num>=10) {  
     //throw an exception  
     throw new Exception("Value must be less than 10");  
   }  
   return true;  
}  
  
//trigger an exception in a "try" block  
try {  
   checkNumber(4);  
   //If the exception throws, below text will not be display  
   echo 'If you see this text, the passed value is less than 10';  
}  
  
//catch exception  
catch (Exception $e) {  
   echo 'Exception Message: ' .$e->getMessage();  
}  
?>

In the above code exception is being thrown from the function but the try catch block in not inside the function rather the function call is enclosed inside try catch block.

The Finally block

This block of code is used to execute code that need to executed always irrespective of the exception whether it has occurred or not.

For example:

try {
  
} catch (Exception $e) {
 
} finally {
  // code, it'll always be executed
}

Finally block is generally used to clean up the resources being used during the program like open db connections or open files etc.

Custom Exceptions in PHP

We can create our own exception classes in PHP if our requirement is not satisfied with inbuilt classes available in PHP. In order to create our own exception classes we need to create a new class that derives from the base Exception class.

<?php  
//Custom Exception classes that derives from the exception class
class DivideByZeroException extends Exception { }  
class DivideByNegativeNoException extends Exception { }  

function checkdivisor($dividend, $divisor){  
  try {  
      if ($divisor == 0) {  
        //throw object of the custom exception class
        throw new DivideByZeroException;  
      }   
      else if ($divisor < 0) {  
         throw new DivideByNegativeNoException;   
      }   
      else {  
        $result = $dividend / $divisor;  
        echo "Result of division = $result </br>";  
      }  
    }  
    catch (DivideByZeroException $dze) {  
        echo "Divide by Zero Exception! </br>";  
    }  
    catch (DivideByNegativeNoException $dnne) {  
        echo "Divide by Negative Number Exception </br>";  
    }  
    catch (Exception $ex) {  
        // if the exception is not caught in the above catch blocks than it will come here
        echo "Unknown Exception";  
    }  
}  
   
    checkdivisor(17, 3);// no exception will be thrown  
    checkdivisor(45, -6);  // Divide by negative number exception will be thrown
    checkdivisor(30, 0);  // Divide by zero exception will be thrown
?>

In the above code we are creating two custom classes that derive from the base exception class. One will be used to throw exception if the divisor is zero and other will be used to throw exception if the divisor is negative.

Function checkdivisor() is called three times to see the different error messages based on the divisor being passed to it either positive, negative or zero.

 

 

Flow Control Statements in PHP

Flow Control Statements in PHP

Flow control statements in PHP are those statements that change the actual flow of the program code execution during runtime. We can execute a set of statements multiple times or skip a set of statements based on some condition.

In PHP we have several types of flow control statements. First we will start with if-else statements.

If-Else Statement in PHP

If block starts with a particular condition that returns a Boolean value based on the the result of that expression which is given in the condition the block of code may or may not execute. In case the condition evaluated to true than if block gets executed otherwise else part of the code gets executed. We can also have if statements without else part it is not mandatory to include else part with every if statement.

if else statement flowchart - Flow Control Statements in PHP

If-Else Statement Flow Chart

Let’s see a simple example explaining the if-else statement. In the following program we are checking a variable value if it is greater than a specified value than we print a message otherwise we will print some other message.

<?php
    $salary = 10000;
    
    if($salary >= 10000)
        echo "<h1>Your salary is greater than 10000</h1>";
    else
        echo "<h1>Your salary is less than 10000</h1>";
?>

Output

Your salary is greater than 10000

If-ElseIf Statement in PHP

We can also check multiple conditions based on which we can execute different code blocks. For example in the following program we are checking if the salary is greater than some specific value based on that we are printing some message in the output.

if else if flow chart in php - Flow Control Statements in PHP

If Else If Flowchart in PHP

<?php
    $salary = 20000;
    
    if($salary >= 20000)
        echo "<h1>Your salary is greater than 20000</h1>";
    elseif ($salary >= 10000)
        echo "<h1> Your salary is greater than 10000</h1>";
    else
        echo "<h1>Your salary is less than 10000</h1>";
?>

Output

Your salary is greater than 20000

Nested if Blocks in PHP

We can also next if block inside another if block. So first the outer if block condition is checked if it comes out to be true than inner if block will be executed. So we can nest if blocks up-to any level while writing code.

Nested If Else Flowchart in PHP - Flow Control Statements in PHP

Nested If Else Flowchart in PHP

<?php
    $nationality = "Indian";
    $age = 10;
    if($nationality == "Indian")
    {
        if($age >= 18)
        {
            echo "<h1>You are eligible to vote</h1>";
        }
        else
        {
            echo "<h1>Your age is less than 18.So your are not eligible";
        }
    }
    else
    {
        echo "<h1>You are not eligible to vote</h1>";
    }
?>

Output

Your age is less than 18.So your are not eligible

Switch Statement in PHP

We can make use of switch statement to make our task easier if we want to check for multiple conditions rather than using if-elseif statement.

In Switch statement we can pass any character,number or string value and can execute different set of code based on the value of the variable being passed to it. Its not mandatory to pass a boolean expression to switch statement.

Every block of code ends with break statement if we do not include break at the end of code block the control flow will skip to the next case and keeps on executing unless and until it finds the break statement.

In case none of the switch case matches than default block will be executed. Their can be only one default block in a switch statement.

<?php
    $num=10;
    
    switch($num)  
    {
        case 10:
            echo "The number is 10";
            break;
        case 20:
            echo "The number is 20";
            break;
        default:
            echo "The number does not match any of the given conditions";
    }
    
?>

Output

The number is 10

Switch statement is fall through as explained earlier if the break statement is not found in any case block than the flow of code will jump to next case block until it founds the break statement even if the condition of the following case blocks matched or not.

<?php
    $num=20;
    
    switch($num)  
    {
        case 10:
            echo "The number is 10";
            break;
        case 20:
            echo "The number is 20<br/>";
        case 30:
            echo "The number is 30<br/>";
        default:
            echo "The number does not match any of the given conditions";
    }
    
?>

Output

The number is 20
The number is 30
The number does not match any of the given conditions

Loops in PHP

Loops are used in PHP to execute a set of statements repeatedly. Different types of loops that we can make use of in PHP are:

For loop

It is used when we want to execute code a specific number of times. We can start by initializing a variable and increment its value and check its value during each iteration to check whether to continue execution of the loop or not.

For Loop Flowchart in PHP - Flow Control Statements in PHP

For Loop Flowchart in PHP

<?php
    
    for($i=1;$i<=10;$i++)
    {
        echo $i." ";
    }
?>

Output

1 2 3 4 5 6 7 8 9 10

While loop

This loop is used to execute a set of statements unless and until a specific condition does not evaluate to false.

While Loop Flowchart in PHP - For Loop Flowchart in PHP

While Loop Flowchart in PHP

<?php
    $num=10;

    while($num>=1)
    {
        echo $num." ";
        $num--;
    }
?>

Output

10 9 8 7 6 5 4 3 2 1

Do while loop

Do while loop is used when you want to execute the code at least once. The loop condition will not be checked during the first execution. The loop will terminate when the condition evaluates to false.

<?php
    $num=10;

    do
    {
        echo $num." ";
        $num--;
    }while($num!=0);
?>

Output

10 9 8 7 6 5 4 3 2 1

Foreach loop

foreach is used to loop through array elements.

<?php
    $num=array(10,20,30,40);

    foreach($num as $num)
    {
        echo $num." ";
    }    
   
?>

Output

10 20 30 40

Break Statement in PHP

While programming their may arise a need when we need to terminate the loop before it completely executes based on some condition. We can make use of break statements for that.

Break Statement in PHP - Flow Control Statements in PHP

Break Statement in PHP

<?php
    $num=array(10,20,30,40);

    foreach($num as $num)
    {
        echo $num." ";
        if($num == 30)
            break;
    }    
   
?>

Output

10 20 30

Continue Statement in PHP

Continue statement is used when we want to skip current iteration of the loop based on some condition.

Continue Statement in PHP - Flow Control Statements in PHP

Continue Statement in PHP

<?php
    $num=array(10,20,30,40);

    foreach($num as $num)
    {
       if($num == 30)
            continue;
        echo $num." ";
       
    }    
?>

Output

10 20 40