PHP Exception And Error Handling Tutorial

If a specific error occurs, PHP exceptions are used to alter a script’s normal flow. We’ll talk about PHP-Exception And Error Handling today. Prior to these, we also covered Forms in PHPPHP SessionPHP Operators, and PHP Cookies, PHP-File Uploading | Example. If you don’t know about these, then act quickly!

What is an Exception?

An error is an unpredicted program outcome that the program is unable to handle. The program is fixed to fix errors. An infinite loop that never ends would be an example of an error. Unexpected program results that can be handled by the program itself are an exception.

A new object-oriented method of handling errors was introduced with PHP 5.

If a specific error (exceptional) condition arises, exception handling is used to alter the normal flow of the code execution. This circumstance is known as an exception.

Typically, when an exception is triggered, the following occurs:

  • It is saved in the current code state.
  • The code will transition to a built-in (personalized) exception handler function.
  • The handler may then choose to continue the script from the saved code state, stop it from running, or start it again elsewhere in the code, depending on the circumstances.

We’ll demonstrate various error-handling techniques:

  • Exceptions’ fundamental use
  • making a personalized exception handler
  • numerous exceptions
  • Rejecting a rule again
  • the top-level exception handler setting

Why is PHP using Exception Handling?

The following are exception handling’s primary benefits over error handling.

  • Error handling code is separated from regular code: There is always an if-else block to handle errors in traditional error handling code. Code to handle errors and these conditions got mixed up, making it unreadable. Try Catch makes block code readable.
  • Organization of error types: Both fundamental types and objects may be thrown as exceptions in PHP. It can arrange exception objects in a hierarchy, put them in namespaces or classes, or sort them into different types.

NOTE: Using an exception to jump to a different location in the code at a specific point is not recommended; exceptions should only be used in error-related situations.

Basic Use of Exceptions

When an exception is raised, the code that follows it is not run, and PHP looks for the appropriate “catch” block instead.

A fatal error will be generated with the message “Uncaught Exception” if an exception is not caught.

Let’s attempt to throw an exception while not catching it:

<?php

// PHP Program to illustrate normal
// try catch block code
function demo($try) {
	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 none.');
				
			// 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 rised
demo(5);

// Exception will be rised here
demo(0);
?>
OUTPUT:
 Before try block
 Inside try block
 Exception CaughtNumber is none.
 After catch (will be always executed) Before try block
 Inside try block
 Exception CaughtNumber is none.
 After catch (will be always executed)

Try, throw and catch

We must write the appropriate code to handle an exception in order to prevent the error from the previous example.

An appropriate exception code should contain:

  1. try: A “try” block should surround any function that uses an exception. The code will continue operating normally if the exception does not occur. However, an exception is “thrown” if the trigger occurs.
  2. throw: An exception is triggered in this manner. There must be at least one “catch” for every “throw.”
  3. catch: Using a “catch” block, an exception is retrieved and an object containing its details is created.

PHP Error Handling

Depending on your configuration settings, PHP displays the error message with details about the error that occurred in the web browser when an error occurs.

Error handling options in PHP are numerous.

We’ll examine three (3) frequently employed techniques;

Die statements–  The echo and exit functions are combined into one with the die function. When we want to output a message and halt the script’s execution when an error occurs, it is very helpful.

Custom error handlers – These user-defined procedures are used when an error occurs.

PHP error reporting – Your PHP error reporting settings will determine the error message. When you are working in a development environment and are unsure of the error’s root cause, this method is very helpful. You can use the information displayed to assist in application debugging.

Error handling examples

Now let’s look at a few straightforward examples with error handling procedures.

Let’s imagine that we have created a program that stores data in text files. Before attempting to read data from the file, we might want to make sure that it is there.

Reporting LevelDescriptionExample
E_WARNINGonly shows warning messages. does not halt the script’s execution.error_reporting(E_WARNING);
E_NOTICEDisplays notices that may appear during a program’s normal execution or that may indicate an error.error_reporting(E_ NOTICE);
E_USER_ERRORDisplays custom error handlers, or user-generated errors.error_reporting(E_ USER_ERROR);
E_USER_WARNINGdisplays warnings created by userserror_reporting(E_USER_WARNING);
E_USER_NOTICEdisplays notices submitted by userserror_reporting(E_USER_NOTICE);
E_RECOVERABLE_ERRORdisplays errors that can be handled using custom error handlers but are not fatal.error_reporting(E_RECOVERABLE_ERROR);
E_ALLdisplays all warnings and errorserror_reporting(E_ ALL);

Difference between Errors and Exception

  • Errors are typically unrecoverable, while exceptions are thrown and designed to be caught.
  • Object-oriented thinking is used to handle exceptions. It follows that a new exception object containing the exception details is created whenever an exception is thrown.
ERROREXCEPTION
The procedural approach leads to errors.Exceptions are a programming technique that is object-oriented.
PHP’s built-in error handling is very straightforward. The browser receives an error message that includes the filename, line number, and message describing the error.Throw new Exception() is used for basic exception handling; the try-and-catch method is required for advanced exception handling.
Using the PHP die() function, this is possible.If a specific error occurs, exceptions are used to alter a script’s normal flow.
Most errors are brought on by the environment that a program is running in.Program exceptions are the result of the program itself.

NOTE: Although PHP is an exception-light language by default, working with object-oriented code allows you to turn errors into exceptions.

The methods for exception objects are shown in the table below.

MethodDescriptionExample
getMessage()reveals the message of the exception<?php echo $e->getMessage(); ?>
getCode()displays the exception’s identification code in numeric form<?php echo $e->getCode(); ?>
getFile()the file name and location where the exception occurred are displayed<?php echo $e->getFile(); ?>
getLine()the line number where the exception was displayed<?php echo $f->getLine(); ?>
getTrace()displays a backtrace array before the exception<?php print_r( $f->getTrace()); ?>
getPrevious()The previous exception is shown prior to the current one, and the backtrace is shown as a string rather than an array.<?php echo $f->getPrevious(); ?>
getTraceAsString() the prior exception is shown before the current exception.<?php echo $f->getTraceAsString(); ?>
__toString()string that displays the entire exception<?php echo $f->__toString(); ?>

Multiple Exceptions

Numerous exceptions To handle the thrown exceptions, use multiple try-catch blocks. When; multiple exceptions are helpful.

  • Depending on the exception raised, you want to display a specific message.
  • Depending on the exception thrown, you want to carry out a specific operation.

Creating Custom Exception

By extending the Exception class, you can create user-defined exceptions. Learn how to create user-defined exceptions by looking at the code below –

<?php  
class DivideByZeroException extends Exception { }  
class DivideByNegativeNoException extends Exception { }  
function checkdivisor($dividend, $divisor){  
    // Throw exception if divisor is zero  
  try {  
      if ($divisor == 0) {  
        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) {  
        echo "Unknown Exception";  
    }  
}  
   
    checkdivisor(18, 3);  
    checkdivisor(34, -6);  
    checkdivisor(27, 0);  
?>  
OUTPUT:
Result of division = 6
Divide by Zero Exception!
Divide by Negative Number Exception!

Summary

  • Unexpected results from PHP code are known as errors.
  • Error handling enhances the efficiency of the application.
  • The way that PHP reports errors can be altered using built-in functions.
  • Exceptions are similar to errors, but when they are thrown, the catch block can be used to catch them.
  • Displaying error messages that include error details is regarded as a poor security practice.

You Might Like

Leave a Reply

Your email address will not be published. Required fields are marked *