⇧
vadnica-logo
Editor My Blog Password Manager Finance My Services About the Project Telegram O meni O meni

PHP Exceptions

An Exception is a special object that describes an error or unexpected behavior of a script. We use them when we want to safely stop or redirect code execution if we encounter a problem that the program cannot automatically handle. We trigger an exception using the throw statement, and we catch it using a try...catch structure, resolving it in time to prevent the entire webpage from crashing.

EXAMPLE
RESULT
The result will be displayed here...

Built-in Methods of the Exception Object

When we catch an exception inside a catch block, we gain access to an object that contains precise data about where and why something went wrong. To retrieve this data, we use the following methods:

  1. Exception(): The constructor used to create a new exception object (used as throw new Exception("Message")).
  2. getMessage(): Returns the descriptive error message that was defined when the exception was thrown.
  3. getCode(): Returns the numeric error code for easier identification or categorization of issues.
  4. getFile(): Returns the full (absolute) path to the file where the exception occurred.
  5. getLine(): Returns the exact line number that triggered the exception.
  6. getTrace(): Returns a detailed array of all function calls and files that led up to the error.
  7. try ... catch ... finally: The main structure for handling exceptions. The finally block is always executed (regardless of whether an error occurred or not), which is ideal for tasks like closing open files or database connections.

💡 When to use exceptions in practice?

Exceptions are not intended for ordinary syntax errors (like a forgotten semicolon). We use them to handle external, unpredictable situations that the programmer has no direct control over—for example, when a remote API server fails to return data, when a user uploads the wrong file type, or when a database connection drops. By catching the error, you can display a friendly notification to the user instead of a raw red system error page.