PHP Exceptions

Today we will learn to handle errors using exception handling in this PHP Exceptions tutorial.

  • Exception handling was introduced in PHP version 5. It is a new object oriented way of dealing with errors.
  • Exceptions are the arbitrary errors that occur in the code which are handled using exception handling.
  • It allows the programmer to have more fine control on the code when errors occur in it.
  • Exception handling in PHP is similar to the exception handling used in other programming languages.
  • There is a class called Exception which is a base class for all pre-defined exceptions. Some of the exceptions are shown below:
    • InvalidArgumentException,
    • OutOfRangeException,
    • OutOfBoundsException,
    • RuntimeException, etc.
  • Exception handling is carried out using four important keywords:
    • try
    • throw
    • catch
    • finally
  • try: The code in which you feel that error can occur during execution is called as risky code. This risky code is put in the try block. If the error does not occur, the code executes normally but if the error occurs, an exception is thrown and is catched in the catch block.
  • throw: The exception if occurred, is thrown using throw keyword.
  • catch: The thrown exception is catched or retrieved in the catch block and it creates an object that contains the exception information.
  • finally: Anything written in the finally block executes always. It is not compulsory to use finally block but if used it executes irrespective of the error occurs or not.
  • Let us see how a program terminates abruptly without exception handling.
  • To demonstrate it, create a new folder with name exceptions in the htdocs folder in xampp folder. Open a new notepad++ document and save it as index.php in the newly created exceptions folder.
  • The example code written in index.php page is given below:
  • <html>
    <head>
    <title>PHP Exceptions</title>
    </head>
    <body>
    <?php
    	$a=10;
    	$b=0;
    	$c=$a/$b;
    	echo "Division of $a by $b is $c";
    ?>
    </body>
    </html>
    
  • Here, we have a variable $a with value 10 and another variable $b with value 0.
  • The value in $a is divided by value in $b and the output is stored in $c.
  • The output is displayed using echo statement.
  • But here as we are dividing the value in $a i.e. 10 by 0 i.e. the value in $b, a divide by zero exception occurs as shown in the figure below:
  • Just open the browser and write localhost/exceptions in the address bar of the browser and see the output.
  • error_witout_exception-handling
    fig 1

  • Here we got an error and our program terminated abruptly. To take care that our program should not terminate abruptly and a proper understandable error message is given, it is very important to use exception handling in the program.
  • So let us learn to handle exceptions using try, catch and throw keywords.
  • Handling exceptions using try, catch and throw keywords:
    • Let us first see the syntax of how to apply the keywords for exception handling.
    • <?php
      	try{
      		-
      		-
      		//risky code
      		-
      		//if an error occurs
      		throw new Exception(“error msg”);
                   }
      	   catch(Exception object)
      	   {
                   	//Statement for error message.
                   }
      	   finally
      	   {
          		//Statement to be executed compulsorily
                }
      ?>
      
    • In the above syntax the try block contains the risky code. It throws an error using the throw keyword, if it occurs.
    • The thrown error is catched in the catch block.
    • The Exception is a class that is predefined. Similarly there are different pre-defined exceptions classes which are the sub-classes of Exception class, some of them are listed before.
    • The catch function takes an object of one of these exception classes as a parameter and gives an accurate exception message.
    • One try block can have any number of catch blocks. Minimum one catch block is must.
    • For multiple catch blocks, the catch blocks for the sub classes of Exception class should appear before the catch block for Exception class. Because if the catch block for Exception class is placed first, it will catch all the exceptions as it is a base class for exceptions and it will not allow the control to reach the catch blocks of its sub classes.
    • The finally block is the block whose statements execute compulsorily.
    • It executes always, no matter may an error/exception occur or the program executes normally.
    • Let us see an example that uses exception handling.
    • We will use the same program that was used for the output in figure 1 but with exception handling and see the output:
    • The code written in the index.php page is given below:
    • <html>
      <head>
      <title>PHP Exceptions</title>
      </head>
      <body>
      <?php
      	//code with exception handling
      	try
      	{
      	$a=10;
      	$b=0;
      	if($b<=0)
      		throw new Exception("Denominator should not be 0 or less than that.");
      	$c=$a/$b;
      	echo "Division of $a by $b is $c";
      	}
      	catch(Exception $e)
      	{
      		echo 'Error: '.$e->getMessage();
      	}
      	
      ?>
      </body>
      </html>
      
    • Here we have written the risky code of division in try block.
    • An exception is thrown using throw keyword with message Denominator should not be 0 or less than that. This exception is thrown if the denominator is less than or equal to zero.
    • If this exception is thrown, the further statements in try block are not executed.
    • The thrown exception is catched in the catch block. The object of the Exception class $e is used to access the exception message using getMessage() method as shown in the following statement:
    • echo 'Error: '.$e->getMessage();
    • Since $e is an object of a class, any method through it is called using arrow operator (->).
    • The output is shown below:
    • error_with_exception_handling
      fig 2

    • Just compare fig 1 and fig2; you will understand the use of exception handling. In fig 1, the program has been abruptly terminated but in fig 2, a proper error message is given and the program has not terminated abruptly.
  • Handling multiple exceptions:
    • We can handle multiple exceptions in a single program.
    • But before handling multiple exceptions it should be kept in mind that the catch blocks that use sub-classes of Exception class to handle exceptions should be placed before the catch block that use base class, Exception to handle the exceptions.
    • This is because the base class can handle every exception, thus it will not allow the control to reach the sub- classes if they are used after it.
    • Let us see an example. Write the following code in index.php page:
    • <html>
      <head>
      <title>PHP Exceptions</title>
      </head>
      <body>
      <?php
      	//multiple exceptions handled
      	try
      	{
      		$games=array("Chess","Badminton","Table-Tennis","snake-n-Ladder");
      		
      		$length=-10;
      		$breadth=-5;
      		
      		if($length<0 && $breadth<0)
      			throw new InvalidArgumentException("Length and Breadth should have positive values.");
      			
      		//area of rectangle
      		$area=$length*$breadth;
      		echo "Area of rectangle = $area sq units.<br>";
      		
      		//array elements
      		echo "<strong>Array Elements: <br></strong>";
      		for($i=0;$i<5;$i++)
      		{
      			if($i==4)
      				throw new OutOfBoundsException("You are accessing outside the bounds of array.");
      			echo $games[$i]."<br>";
      		}
      	}
      	catch(InvalidArgumentException $ie)
      	{
      		echo $ie->getLine()." : ".$ie->getMessage();
      	}
      	catch(OutOfBoundsException $oe)
      	{
      		echo $oe->getLine()." : ".$oe->getMessage();
      	}
      	catch(Exception $e)
      	{
      		echo "Error : ".$e->getMessage();
      	}
      	
      ?>
      </body>
      </html>
      
    • In the above code we have handled multiple exceptions such as InvalidArgumentException, OutOfBoundsException, etc.
    • First we have declared an array $games with 4 values and initialized variables $length and $breadth to -10 and -5 respectively.
    • We want to find out the area of rectangle, but we want its length and breadth to be positive. So here we first checked to see if both length and breadth of rectangle are positive or not. If they are not positive, an InvalidArgumentException is thrown and the remaining code in try block is not executed.
    • The thrown exception is matched with the catch blocks one by one to return the correct exception message.
    • In this case the first catch block is matched and the following output is shown:
    • multiple_exceptions_handling_error_1
      fig 3

    • Now let us change the values of $length and $breadth variables from -10 and -5 to 10 and 5 respectively. Save the changes and once again reload the browser.
    • This time no InvalidArgumentException will be thrown, because we have positive values in variables $length and $breadth. The area of rectangle will be calculated and displayed successfully.
    • After this we are trying to display the elements in array $games using a for loop.
    • The loop should iterate 4 times as the array contains 4 elements, i.e. counter should move from 0 to 3 since the array location starts from zero. But the loop is purposefully iterated 5 times i.e. the counter moves from 0 to 4.
    • Here, an array OutOfBoundsException is to be handled, since we are trying to access more elements than are present in the array.
    • So the condition if($i==4) is checked. When this condition is satisfied, an OutOfBoundsException is thrown.
    • The array values are displayed and when the condition $i==4 is satisfied, the exception is thrown.
    • This exception is matched to the catch blocks and the respective error message is shown.
    • The output is shown below:
    • multiple_exceptions_handling_error_2
      fig 4

    • We get the line number where the error occurred using getLine() method. We can also get the file name using getFile() method. The error message is returned through getMessage() method.
    • The catch block that has the object of Exception class as its parameter will handle any other error that occurres, since it a base class of exceptions.
  • Custom Exceptions:
    • Sometimes there are situations in our program where we need to create our own exceptions and use them; these are called as custom exceptions or user-defined exceptions.
    • To create custom exceptions, we need to define a new class that extends Exception class.
    • Then this class can contain different methods that handle the exception.
    • Let us see an example that demonstrates custom exception.
    • Write the following code in index.php file:
    • <html>
      <head>
      <title>PHP Exceptions</title>
      </head>
      <body>
      <?php
      	class RangeExceededException extends Exception
      	{
      		public function exceeded()
      		{
      			echo "Error occurred: ".$this->getLine()." : Number should not exceed value 10.<br>";
      		}
      	}
      	
      	class NegativeNumberException extends Exception
      	{
      		public function negative()
      		{
      			echo "Error occurred: ".$this->getLine()." : Number cannot be negative.<br>";
      		}
      	}
      	try
      	{
      	$x=7;
      	
      		if($x>10)
      			throw new RangeExceededException();
      		else
      		if($x<0)
      			throw new NegativeNumberException();
      		else
      		{
      			$y=$x*$x;
      			echo "Square of $x = $y";
      		}	
      	}
      	catch(RangeExceededException $re)
      	{
      		echo $re->exceeded();
      	}
      	catch(NegativeNumberException $ne)
      	{
      		echo $ne->negative();
      	}
      	catch(Exception $e)
      	{
      		echo $e->getMessage();
      	}
      ?>
      </body>
      </html>
      
    • In the above code we have defined two classes, RangeExceededException and NegativeNumberException that extends/ inherits the Exception class. Since it inherits the Exception class, it can use all the methods written in Exception class.
    • The RangeExceededException is set to be occurred when the value of variable $x exceeds value 10 and the NegativeNumberException is set to be occurred when the number in variable $x is negative.
    • We have declared a function exceeded() in class RangeExceededException and function negative() in class NegativeNumberException.
    • $this used in the functions exceeded() and negative() represents the current object. The method getLine() have been called using $this.
    • When the exception is thrown, it is caught in the catch block and the method is called to display the error message.
    • If no error occurs, square of the value in variable $x is obtained as shown below:
    • no_error_in_custom_exception_eg
      fig 5

    • Now if we change the value of variable $x from 7 to 12, a RangeExceededException will occur and the error message will be shown as follows:
    • range_exceeded_exception_output
      fig 6

    • Similarly, if we change the value of variable $x from 12 to -2, a NegativeNumberException will occur and the error message will be shown as follows:
    • negative_number_exception_output
      fig 7

  • Finally block:
    • The finally block is the most important concept in exception handling.
    • This block when used with try-catch blocks, it allows us to execute the statements written in it always.
    • I mean that the statements written in finally block are executed compulsorily, whatever may happen i.e. it will execute even if a error occurs and it will execute even if the program runs normally.
    • Finally block begins with the word finally followed by opening and closing curly braces.
    • If exception handling is used in a function along with finally block and some value is returned from the function using a return statement, even then the finally block will be executed.
    • This finally block should be used in those programs where you want certain statements to be executed always, inspite of the occurrence of error.
    • Let us have an example to demonstrate a finally block.
    • <html>
      <head>
      <title>PHP Exceptions</title>
      </head>
      <body>
      <?php
      	try
      	{
      		echo "This is a risky code.<br>";
      		throw new Exception("Something went wrong!");
      		
      	}
      	catch(Exception $r)
      	{
      		echo $r->getMessage();
      	}
      	finally 
      	{
      		echo "<br>Welcome to PHP.<br> finally block executes always.";
      
      }
      	
      ?>
      </body>
      </html>
      
    • Here you will see that a statement in try block is executed, and then an exception is thrown.
    • This exception is catched in the catch block and error message is displayed.
    • Then finally block executes and displays the statements in it.
    • The output is shown below:
    • finally_output
      fig 8

    • In the functions returning a value the finally block executes before the value is returned by the function.

Thus we studied the use and importance of exception handling in this PHP Exceptions tutorial.

Previous articleMulti-Dimensional Arrays in PHP
Next articlePHP Email

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -