In this tutorial, you shall learn how to explicitly throw an exception in PHP, with the help of example programs.
PHP – Throw Exception
In PHP, we can exclusively throw an exception object using throw keyword.
Syntax
The syntax to throw an exception, using throw keyword is
throw exception_object;
Where exception_object
is created from a built-in exception class or a custom exception class.
Examples (2)
1. Throw Built-in Exception
In the following program, we throw an Exception class object from try-block using throw keyword.
PHP Program
<?php
try {
//some code
throw new Exception("An excpetion occurred.");
} catch (Exception $e) {
//handle exception
echo $e->getMessage();
}
?>
Output
References
2. Throw Custom Exception
In the following program, we define a custom exception, MyException
and throw this exception from try-block using throw keyword.
PHP Program
<?php
class MyException extends Exception { }
try {
//some code
throw new MyException("This is a message from MyException.");
} catch (MyException $e) {
//handle exception
echo $e->getMessage();
}
?>
Output
References
Conclusion
In this PHP Tutorial, we learned how to create a custom exception class and throw this custom exception object in a try-catch statement.