Exception Handling in PHP

Exception handling is a powerful PHP mechanism for dealing with runtime errors (runtime errors are called exceptions). So that the application’s normal flow can be maintained.

The main purpose of using exception handling is to maintain the normal execution of the application.

What is an Exception?

An exception is an unexpected result of a programme that can be handled by the programme itself. An exception, in essence, disrupts the normal flow of the programme. However, it differs from an error in that an exception can be handled, whereas an error cannot.

In other words, “an unexpected consequence of a programme is an exception, which can be handled by the programme itself.” In PHP, exceptions can be thrown and caught.

Why needs Exception Handling?

Exception handling is a strong technique provided by PHP. It gives you the ability to handle runtime issues like IOException, SQLException, ClassNotFoundException, and others. The divide by zero exception, which is an arithmetic exception, is a popular example of exception handling.

Exception handling is nearly identical across all programming languages. When a stated error condition happens, it alters the regular flow of the programme, and this circumstance is known as an exception. For this purpose, PHP provides the following keywords:

try –

The try block contains code that could throw an exception or where an exception could occur. When an exception occurs within the try block during code execution, it is caught and resolved in the catch block. The try block must be followed by a catch or finally block. A try block can be followed by as few as one or as many as any number of catch blocks.

catch –

catch –

The catch block includes the code that is executed when an exception is thrown. It is never used without a try block. When an exception occurs, PHP looks for the appropriate catch block.

throw –

It is a keyword for throwing an exception. It is also beneficial to record all of the exceptions that a function throws but does not handle. Keep in mind that each throw must include at least one “catch.”

finally –

In PHP, the finally block contains code that is used for cleanup. It basically performs the program’s core code.

What happens when an exception is triggered –

  • The current state of code is saved.
  • The code’s execution is shifted to a present exception handler function.
  • Depending on the situation, the handler can pause programme execution, resume programme execution from the saved code state, or continue programme execution from another position in the code.

Advantage of Exception Handling over Error Handling

Exception handling is a critical mechanism in PHP that has several advantages over error handling.

Grouping of error types –

In PHP, both basic and object exceptions can be thrown. It may build a hierarchy of exception objects, group exceptions into classes, and classify them based on their types.

Keep error handling and normal code separate –

To manage errors in classical error handling, an if-else block is employed. Because the code for handling errors and conditions became intermingled, the code became illegible. The exception is kept isolated from the logic within the try-catch block, and the code becomes readable.

Examples

Learn with the help of examples how exception handling works in PHP-

Example 1

Let’s take an example to explain the common flow of throw and try-catch block:

<?php
//user-defined function with an exception
function checkNumber($num) { if($num>=1) {
//throw an exception
throw new Exception(“Value must be less than 1”);
}
return true;
} //trigger an exception in a “try” block
try {
checkNumber(5);
//If the exception throws, below text will not be display
echo ‘If you see this text, the passed value is less than 1’;
} //catch exception
catch (Exception $e) {
echo ‘Exception Message: ‘ .$e->getMessage();
}
?>

Output:

Exception Message: Value must be less than 1

Example 2: Creating Custom Exception

Extending the Exception class allows you to construct user-defined exceptions. Examine the code below to see how to create a user-defined exception –

<?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
“;
}
}
catch (DivideByZeroException $dze) {
echo “Divide by Zero Exception!
“;
}
catch (DivideByNegativeNoException $dnne) {
echo “Divide by Negative Number Exception
“;
}
catch (Exception $ex) {
echo “Unknown Exception”;
}
}

Output:

Result of division = 6
Divide by Zero Exception!
Divide by Negative Number Exception!

Leave a Comment

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