What is the use of the throw keyword in PHP?
Last Updated :
13 Feb, 2024
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:
- The
throw
keyword is followed by the new
keyword, which instantiates an exception object.
- The exception object typically contains information about the error, such as an error message or code.
- When
throw
is executed, PHP immediately stops executing the current code block and looks for an appropriate exception handler to handle the thrown exception.
Usage:
- Error Signaling:
throw
is used to signal an error or exceptional condition within the code.
- Exception Handling: Thrown exceptions are caught and handled by exception handlers, typically defined within
try-catch
blocks.
- Custom Error Messages: Exception objects can be customized to include specific error messages, codes, or additional data to provide context for the exception.
Example: Implementation to show the use of the throw keyword in PHP.
PHP
<?php
function divide( $dividend , $divisor )
{
if ( $divisor == 0) {
throw new Exception( "Division by zero" );
}
return $dividend / $divisor ;
}
try {
echo divide(10, 0);
} catch (Exception $e ) {
echo "Exception caught: " . $e ->getMessage();
}
?>
|
Output
Exception caught: Division by zero
Share your thoughts in the comments
Please Login to comment...