PHPPHP17 min read

Exceptions in PHP (Try/Catch Like a Pro)

Use exceptions for cleaner error handling and create custom exceptions for business logic.

Olivia Grant
October 24, 2025
4.9k194

Exceptions make error handling cleaner than checking return values everywhere.

Basic try/catch

try {
  if ($amount <= 0) {
    throw new Exception("Amount must be positive");
  }
  echo "OK";
} catch (Exception $e) {
  echo $e->getMessage();
}

Custom exception example

class PaymentFailedException extends Exception {}

function chargeCard(float $amount) {
  if ($amount > 5000) {
    throw new PaymentFailedException("Charge declined");
  }
}

Why custom exceptions help

They let you catch specific problems differently.

try {
  chargeCard(7000);
} catch (PaymentFailedException $e) {
  echo "Payment issue: " . $e->getMessage();
}

Next: CORS, make your API work with frontend apps securely.

#PHP#Error Handling#Advanced