Glossary

Exception in programming

Exceptions separate the ordinary result of an operation from a situation another layer must handle: a rule violation, an unavailable service, or an unexpected technical error.

Short definition

An exception interrupts normal execution and looks for a matching handler.

After throw, PHP stops the rest of the current path and walks up the call stack towards a matching catch. If it finds none, the exception reaches the global handler or the application terminates with an error. A stack trace is useful input for debugging, but does not automatically reveal the underlying cause. The finally block is for cleanup that should run whether the try block succeeds or an exception is caught.

The thrown object must implement Throwable. In PHP, both Exception and Error fall under it; a custom domain or application exception commonly extends Exception or one of its descendants. Catching Throwable is useful at the application’s outermost boundary for safe logging, but it should not conceal programming errors inside ordinary logic.

Use cases

Where an exception describes a genuinely exceptional state

An exception is a signal to the calling layer, not a substitute for every if branch and every form validation message.

  • a prohibited order or payment state transition
  • a timeout or invalid response from an external marketplace API
  • an error while storing data or a database constraint violation
  • translating a technical error into a clear application error
  • rolling back a transaction and safely terminating an import or worker

Practical example

Translating a shipping provider error into application meaning

An application service does not have to return an ambiguous boolean false when it cannot create a label. It catches a specific technical error, retains it as the previous exception, and passes a use-case-specific exception to the higher layer. The HTTP controller then decides which safe response to show the client.

PHP

try {
    $label = $carrierClient->createLabel($shipment);
} catch (CarrierTimeout $exception) {
    throw new ShippingTemporarilyUnavailable(
        'Dopravce nyní neodpovídá.',
        previous: $exception,
    );
}

How it works

From an error to a safe result for the user

The appropriate place to catch an exception depends on who can genuinely resolve the state meaningfully.

  1. Problem detection A domain rule or infrastructure detects a state in which normal execution cannot continue.
  2. Throw The code throws a specific Throwable; subsequent lines in the current branch no longer run.
  3. Propagation The exception passes through calling code until it reaches a matching catch.
  4. Handling The layer able to decide rolls back, retries, logs, translates, or rethrows the exception.
  5. Application boundary A controller, command, or global handler maps the state to a safe HTTP response or task result.

Main components and concepts

The exception type carries meaning; catch determines responsibility.

Precise types and clear boundaries are usually more useful than one generic catch that suppresses everything.

throw, try, and catch

throw creates an exceptional execution path. try delimits a risky operation, and catch handles a specific type that it knows how to resolve.

finally

Used to clean up resources or restore local state. It should not replace the original problem with another exception without a very good reason.

Exception, Error, and Throwable

Throwable is the common contract for thrown objects. Exception typically represents an application or library error, while Error can arise from a problem in language execution.

Exception translation

An infrastructure detail can be translated at an adapter boundary into an exception meaningful to the application while retaining the original cause as the previous exception.

Error response

An HTTP response or user message must not contain internal paths, passwords, SQL, or a stack trace; those belong in a protected log.

Benefits and limitations

Exceptions make failures more precise but can obscure program flow.

Benefits

  • separation of the ordinary result from the error path
  • a specific type carries meaning for the calling layer
  • the original cause can be retained for diagnosis
  • finally and transactions help clean up after a failure

Common mistakes

  • catching Throwable inside ordinary logic and continuing silently
  • displaying an internal message or stack trace to the user
  • using exceptions as a substitute for every expected if branch
  • losing the original cause when translating infrastructure errors
  • blindly retrying after a timeout without idempotence or a limit

When it makes sense

Catch it where the state can genuinely be resolved.

A domain object can throw an exception when an invariant is violated. An external service adapter can translate a technical error into an application type. Only the entry point—an HTTP controller, CLI command, or worker—usually knows whether to return a response to the user, retry the task, or mark it as failed.

Wrapping every method in its own try/catch is not appropriate. If a layer cannot add a decision, cleanup, or useful context, it is often better to let the exception continue to a place that can actually handle it.

What to consider

An error should be safe for the client and useful for operations.

A well-handled exception preserves diagnostic information without exposing internal details outside the application.

  • catch the most specific type that the layer can actually handle
  • retain the previous exception for diagnosis when translating an error
  • roll back or release a resource before returning from the operation
  • map application errors to consistent and safe responses
  • test important failure scenarios and their side effects

Common questions

Exceptions, Throwable, and error states in PHP

Is an exception the same as an HTTP error?

No. An exception is an object that affects execution flow inside PHP. An HTTP status code is a response to a client; a controller can translate an exception into such a response.

When should Throwable be caught?

Typically at the application’s outermost boundary, where an unexpected failure must be logged safely and a generic response returned. Inside ordinary logic, it is better to catch specific exceptions.

Should I always throw an exception for an invalid form?

Not necessarily. Expected input errors are often returned as a validation result. An exception makes more sense when a rule is violated and the current layer cannot continue normally.

How do exceptions relate to a database transaction?

If an operation fails in the middle of a transaction, the exception handler must ensure a rollback or use a transactional API that performs it. Otherwise, data may remain in an unexpected state.

How I use PHP in practice

I design error states together with integration and data boundaries.

For APIs, imports, and e-commerce processes, I address external service failures, retries, idempotence, and safe logging alongside the successful path.

Request a call

I will call you on the next working day between 9:00 and 17:00.

You can also call me directly.

+420 605 181 728

Leave your phone number and send a callback request.

By sending, you agree to processing your data in order to handle your request.