Open In App

What is the use of the throw keyword in PHP?

In PHP, the throw the keyword is used to manually trigger or “throw” an exception. Exceptions are a way to handle errors or exceptional conditions in PHP code by interrupting the normal flow of execution and transferring control to an exception handler.

Syntax:

throw new Exception("Error message");

Important:

Usage:

Example: Implementation to show the use of the throw keyword in PHP.




<?php
// Throw an exception when a division by zero occurs
function divide($dividend, $divisor)
{
    if ($divisor == 0) {
        throw new Exception("Division by zero");
    }
    return $dividend / $divisor;
}
 
try {
    // Attempt to perform division
    echo divide(10, 0);
} catch (Exception $e) {
    // Handle the exception
    echo "Exception caught: " . $e->getMessage();
}
 
?>

Output
Exception caught: Division by zero


Article Tags :