Exceptions in PHP (Try/Catch Like a Pro)
Use exceptions for cleaner error handling and create custom exceptions for business logic.
Exceptions make error handling cleaner than checking return values everywhere. ## Basic try/catch ```php try { if ($amount <= 0) { throw new Exception("Amount must be positive"); } echo "OK"; } catch (Exception $e) { echo $e->getMessage(); } ``` ## Custom exception example ```php 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. ```php try { chargeCard(7000); } catch (PaymentFailedException $e) { echo "Payment issue: " . $e->getMessage(); } ``` > Next: CORS, make your API work with frontend apps securely.