Exceptions are used to change the normal flow of a script when a specified error condition occurs. Unlike regular errors, exceptions are **objects** that contain information about the failure, including the message, file path, and line number.
When an error occurs, you "throw" an exception. This stops the current function's execution and looks for code that can "catch" the error.
<?php
function checkNumber($number) {
if($number > 1) {
// Signals that an exception has occurred
throw new Exception("Value must be 1 or below");
}
return true;
}
?>
Inside an exception, PHP stores several useful pieces of information. The most common methods are:
| Method | Description |
|---|---|
getMessage() |
Returns the message passed to the constructor. |
getCode() |
Returns the error code (if any). |
getFile() |
Returns the full path of the file where the error happened. |
getLine() |
Returns the line number of the error. |
Exception to handle specific types of errors (like
DatabaseException or AuthException).
throw keyword to signal an error.