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 thenew
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 // 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