Exception And Error Handling Tutorial

Exception And Error Handling Tutorial

Exception And Error Handling Tutorial in PHP exceptions are used to change a script’s normal flow when a specific error occurs. Today’s topic will be PHP-Exception and Error Handling. Before these, we also discussed Registration Form Using form Tag, PHP Comments, Require, Include, What are Operators in PHP? If you don’t know about these, then act quickly!

What is an Exception?

Exception And Error Handling Tutorial in PHP error is a program outcome that was not expected and that the program could not handle. Errors in the program have been fixed. An illustration of a mistake would be an endless loop that never ends. The program itself can take unexpected program results, which is an exception.

With PHP 5, a brand-new object-oriented approach to handling errors was presented.

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 elsewhere in the code, depending on the circumstances.

We’ll demonstrate various error-handling techniques: Exception And Error Handling Tutorial

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

Why is PHP using Exception Handling?

(Exception And Error Handling Tutorial) 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, PHP looks for the appropriate “catch” block rather than running the code that follows it.

If an exception is not caught, a fatal error with the message “Uncaught Exception” will be produced.

Let’s try throwing an exception without also 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.

What is Error Handling in PHP

When an error occurs, PHP displays an error message with information about the error that occurred in the web browser, depending on your configuration settings.

In PHP, there are many options for handling errors.

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(); ?>
Exception And Error Handling Tutorial

Summary

  • Errors are outcomes from PHP code that were not expected.
  • Error handling makes the application more effective.
  • The built-in functions in PHP allow you to change how the language reports errors.
  • Exceptions are similar to errors in that they can be caught using the catch block when they are thrown.
  • It is thought to be bad security practice to display error messages with error details.

So in Exception And Error Handling Tutorial we discous all the things about handling the error.

For more read with us, Oraltadalafil

1 thought on “Exception And Error Handling Tutorial”

Leave a Comment

%d bloggers like this: