Limited Offer
60% OFF on all plans!

Error & Exception Handling in PHP

Learn to handle runtime errors and exceptions in PHP using try/catch/finally, custom exception classes, and set_error_handler().

Types of Errors in PHP

PHP has several error levels — from notices and warnings that allow execution to continue, to fatal errors that stop it. Understanding each type helps you respond appropriately.

1. Error Levels

E_NOTICE, E_WARNING, E_ERROR, E_PARSE.

2. Controlling Error Reporting

error_reporting() and display_errors.

try / catch

PHP exceptions are objects thrown with `throw` and caught with `catch`. Unlike errors, uncaught exceptions terminate the script with a fatal error.

1. Basic try-catch

Wrap risky code and handle failures.

2. The Exception Object

Access message, code, file, line, and trace.

3. Multiple catch Blocks

Handle different exception types differently.

4. Catching Multiple Types (PHP 8.0+)

Use | to catch several exceptions in one block.

finally Block

`finally` always executes after try/catch — whether an exception was thrown or not. It is the right place for cleanup like closing files or database connections.

1. Basic finally

Cleanup that always runs.

2. finally with return

finally overrides a return from try or catch.

Custom Exception Classes

Custom exceptions allow you to represent specific error conditions in your application and carry extra context beyond a message string.

1. Creating a Custom Exception

Extend the built-in Exception class.

2. Exception Hierarchy

Structure exceptions for fine-grained catching.

Built-in Exception Classes

PHP 7+ introduced a `Throwable` interface at the top of the hierarchy, with `Error` and `Exception` as its two branches.

1. Throwable Hierarchy (PHP 7.0+)

Error and Exception both implement Throwable.

2. Commonly Used SPL Exceptions

Choosing the right built-in exception type.

Custom Error & Exception Handlers

PHP lets you register global fallback handlers for errors and uncaught exceptions — essential for logging and graceful error pages in production.

1. set_error_handler()

Convert PHP errors into exceptions.

2. set_exception_handler()

Handle uncaught exceptions globally.

3. register_shutdown_function()

Run code even on fatal errors.

Best Practices

Good error handling separates concerns: log everything, show nothing sensitive, recover where possible, fail fast otherwise.

1. Fail Fast with Guard Clauses

Throw early, throw specific.

2. Never Swallow Exceptions Silently

Always log or re-throw.