365 of 410 menu

The throw Command

The throw command is used for explicitly throwing an exception in PHP. It accepts one parameter - an exception object, which must be an instance of a class inherited from the base Exception class. When this function is called, the execution of the current code immediately stops, and PHP attempts to find a corresponding catch block to handle the exception.

Syntax

throw new ExceptionClass(message, code, previous);

Example

A simple example of generating an exception:

<?php $age = -5; if ($age < 0) { throw new Exception('Age cannot be negative'); } ?>

Code execution result:

Fatal error: Uncaught Exception: Age cannot be negative

Example

Example with exception handling:

<?php try { $res = 10 / 0; if (is_infinite($res)) { throw new Exception('Division by zero'); } } catch (Exception $e) { echo 'Error: ' . $e->getMessage(); } ?>

Code execution result:

'Error: Division by zero'

Example

Using a custom exception:

<?php class MyCustomException extends Exception {} try { throw new MyCustomException('Custom error message'); } catch (MyCustomException $e) { echo 'Custom error caught: ' . $e->getMessage(); } ?>

Code execution result:

'Custom error caught: Custom error message'

See Also

  • the try construct,
    which defines a code block for exception handling
  • the catch construct,
    which catches and handles exceptions
  • the Exception class,
    which is the base class for all exceptions
byenru