What are exceptions and how to handle them?

Exception handling is an elegant way to handle errors which are beyond the program’s scope.

Click : https://phpgurukul.com/what-are-exceptions-and-how-to-handle-them/

In this tutorial, we are going to learn how and when to use exception handling and, even more important, when not to use it.
In order to explain the need for exception handling, we will try to see what happens when a program is fed with faulty data. In our example, we will develop the class FuelEconomy that calculates with the method calculate() the fuel efficiency of cars by dividing the distance traveled by the gas consumption.

class FuelEconomy {
// Calculate the fuel efficiency
public function calculate($distance, $gas)
return $distance/$gas;

We will feed the class with the nested array $dataFromCars, in which each nested array has two values: the first value is for the distance traveled and the second value is for the gas consumption. While the first and last nested arrays contain legitimate data, the second nested array provides zero gas consumption and the third nested array has negative gas consumption.

$dataFromCars = array(

Here is what happens when we feed the array to the class:

Warning: Division by zero
From the result, we can see what might happen when we feed the class with faulty data. On the second line, we got a nasty warning for trying to divide by zero while, on the third line, we got a negative value (which is not what we would expect for gas efficiency). These are the kinds of errors that we would like to suppress by using exception handling.

How to throw an exception?
When handling exceptions, we make use of the Exception class, which is a built-in PHP class. We throw the exception with the command throw new Exception() that creates the exception object. Between the brackets of the throw new Exception() command, we write our own custom message that we would like to appear in the case of the exception.
In the example given below, whenever the user tries to feed the class with a gas consumption value that is less than or equal to zero, a custom message is thrown instead of an error.


PHP Gurukul

Welcome to PHPGurukul. We are a web development team striving our best to provide you with an unusual experience with PHP. Some technologies never fade, and PHP is one of them. From the time it has been introduced, the demand for PHP Projects and PHP developers is growing since 1994. We are here to make your PHP journey more exciting and useful.

Website : https://phpgurukul.com

Showing 1 reaction

Please check your e-mail for a link to activate your account.
  • php gurukul
    published this page in Submit Content 2022-09-20 10:17:59 -0700