Exception Handling in PHP

PHP | Exception Handling: Here, we are going to learn about the exception handling, try, catch and throw method, programs, etc.
Submitted by Sayesha Singh, on August 31, 2020

When a program's normal flow is interrupted or interfered due to some event, that event is termed as an exception. The method used to handle an exception is called exception handler and the phenomenon is called exception handling.

If there are chances of some particular error occurring, then it can be managed through exceptions. The errors which are specified and particular are also calledexceptions and to manage them exception handling is learned to modify the code.

What happens when an exception occurs?

Normally when an exception occurs the following thing happens-

  1. The code is saved as it is in its present state.
  2. There will be a predefined(default) function for handling exceptions in PHP which will be called.
  3. It now depends on what action this default exception handler function decides to take. It can either continue the execution of the code from where it was left or from some other line or completely terminate the code execution.

How should exceptions be handled?

There are some methods where one can easily handle and prevent occurring of hurdles while running code:

  1. try, catch and throw
  2. A customized function for handling exceptions
  3. handling many exceptions at a time
  4. throwing an exception again
  5. set top exception handling function

Try, catch and throw method

It is easy to use this method. Some steps need to be followed. They are-

  • Write the code which can generate an exception in a 'try' block. In case there is no exception, the code will work in a normal fashion, and the execution of 'try' block will not interrupt or affect.
  • If the code might generate some exception, it can be generated by And every 'throw' needs a 'catch'.

A 'catch' block catches the exception which was thrown in the code and does what the programmer coded should be done when it is caught.

Program:

<?php
    //creating a function with an exception
    function enter($roll_no) {
        try { 
		// Check if 
		if($roll_no < 0) { 
			 throw new Exception("Roll Number you have entered ".$roll_no. " is not positive \n"); 
			} 
    	} 
	    catch(Exception $e) {
        echo 'Message: ' .$e->getMessage(); exit(0);
       }
      echo("Your entered roll number is ".$roll_no . "\n");
    }
    enter(9);
    enter(-4);
?>

Output:

Your entered roll number is 9
Message: Roll Number you have entered -4 is not positive

Customized function for handling exceptions

For handling exceptions in a better way a class is made containing the exception handling function. This function will be called when an exception occurs in the code. This class is just a customized extension of the exception class.

Program for creating a class:

<?php 
class ex extends Exception { 
	function Message() { 
		// Error message 
		$Msg = 'The code had an attempt to divide a number by zero error on line no  '.$this->getLine(). "\n" 
				. 'Hence the number is now divided by 1 rather than 0'. "\n"	 ; 
		return $Msg; 
	} 
} 

function divide($a,$b) { 
	try { 
		// Check if divisor is 0
		if($b == 0) { 
			throw new ex($b); 
		} 
	} 
	
	catch (ex $e) { 
		// Display custom message 
		echo $e->Message(); 
              //Take an appropriate action for the error...more than                 
              //    just printing a message
		$b=1;
	} 
    //returns valid value by rectifying errors if caught
	return $a/$b;
} 

// This will not generate any exception 
echo ("When the 15 is divided by 3 the result is ");
echo(divide(15,3)."\n"); 
echo ("When the 4 is divided by 0 the result is \n");
// It will cause an exception 
echo(divide(4,0));
?> 

Output:

When the 15 is divided by 3 the result is 5
When the 4 is divided by 0 the result is
The code had an attempt to divide a number by zero error on line no  17
Hence the number is now divided by 1 rather than 0
4

Handling many exceptions at a time

Many exceptions can be handled at a time with multiple catches and throw lines. Each throw has a corresponding catch block.

Program:

<?php 
class ex extends Exception { 
	function Message() { 
		// Error message 
		$Msg = 'The code had an attempt to divide a number by zero error on line no  '.$this->getLine(). "\n" 
				. 'Hence the number is now divided by 1 rather than 0'. "\n"	 ; 
		return $Msg; 
	} 
} 

class ex1 extends Exception { 
	function Message1() { 
		// Error message 
		$Msg1 = 'The code had an attempt to divide a number by negative number on line no  '.$this->getLine(). "\n" 
				. 'Hence the number is now divided by modulus of the divisor'. "\n"	 ; 
		return $Msg1; 
	} 
}

function jsm($a,$b) { 
	try { 
		// Check if 
		if($b == 0) { 
			throw new ex($b); 
		}
		if($b < 0) { 
			throw new ex1($b); 
		}
		
	} 
	
	catch (ex $e) { 
	
		// Display custom message 
		echo $e->Message(); 
		$b=1;
	} 
	catch (ex1 $e) { 
		// Display custom message 
		echo $e->Message1(); 
                  // taking action
		$b= -$b;
	} 
	return $a/$b;
} 

// This will not generate any exception 
echo ("When the 15 is divided by -3 the result is \n");
echo(jsm(15,-3)."\n"); 
echo ("When the 4 is divided by 0 the result is \n");
// It will cause an exception 
echo(jsm(4,0));
?> 

Output:

The code had an attempt to divide a number by negative number on line no  31
Hence the number is now divided by modulus of the divisor
5
When the 4 is divided by 0 the result is
The code had an attempt to divide a number by zero error on line no  27
Hence the number is now divided by 1 rather than 0
4

Throwing an exception again

An exception might be desired to be handled in a very different manner from the default method. An exception can be thrown again inside the ‘catch’ block. Hiding errors generated by the system makes the program more user friendly as there are many errors that are uselessly displayed on the screen for the user.

Program:

<?php 
class ex extends Exception { 
	function Message() { 
		// Error message 
		$Msg = 'The code had an attempt to divide a number by zero error on line no  '.$this->getLine(). "\n" 
				. 'Hence the number is now divided by 1 rather than 0'. "\n"	 ; 
		return $Msg; 
	} 
} 

$dividend=20; $divisor=0;
try {
  try {
    if($divisor ==0) {
      throw new Exception($divisor);
    }
  }
  catch(Exception $e) {
    echo("\nChanging 0 divisor to 1 \n");
    $divisor =1;
    throw new ex($divisor);
  }
}
catch (ex $e) {
  echo $e->Message();
}
echo("\n Quotient ".($dividend/$divisor));
?>

Output:

Changing 0 divisor to 1
The code had an attempt to divide a number by zero error on line no  21
Hence the number is now divided by 1 rather than 0

Quotient 20

Set_exception_handler() function:

This function lets the programmer modify functions to make the error handling functions.

Program:

<?php
    function ex($exception) {
      echo "<b>Exception:</b> " . $exception->getMessage();
    }

    set_exception_handler('ex');

    $no=0;
    $factorial=1;

    //Since no=0 then if block will be executed
    if($no==0)
    // any line of the code after throw new exception doesn't
    //work and code ends
    throw new Exception('Uncaught Exception occurred');
    for($i=$no;$i>0;$i--)
     $factorial=$factorial * $i;
    echo("answer ".$factorial); 
?>

Output:

<b>Exception:</b> Uncaught Exception occurred

Program:

<?php
    function ex($exception) {
      echo "<b>Exception:</b> " . $exception->getMessage();
    }
    
    set_exception_handler('ex');
    
    $no=5;
    $factorial=1;
    
    //if is false and not executed
    if($no==0)
        throw new Exception('Uncaught Exception occurred');
    for($i=$no;$i>0;$i--)
        $factorial=$factorial * $i;
    echo("answer ".$factorial); 
?>

Output:

answer 120

Important note for exceptions:

There are some rules that should be remembered when trying to catch exceptions-

  1. Each 'try' or 'throw' block has to have a corresponding 'catch' block.
  2. Various types of classes of exceptions can be caught by using different 'catch' blocks.
  3. Better to enclose the part of the code in a 'try' block if it has a more probability of generating errors and exceptions.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.