try...catch...finally & Custom ExceptionsExceptions are error objects thrown when an unexpected runtime error occurs. Exceptions interrupt normal script flow and can be caught and handled gracefully using try...catch...finally blocks.
All throwable errors implement the Throwable interface:
ThrowableException (Application-level recoverable exceptions)Error (PHP engine internal errors, e.g. TypeError, ParseError)flowchart TD
A["Try Block Execution"] --> B{"Exception Thrown?"}
B -- No --> C["Skip Catch; Execute Finally"]
B -- Yes --> D{"Match Exception Catch Type"}
D -- Match CustomException --> E["Execute Custom Catch Block"]
D -- Match Throwable --> F["Execute Fallback Catch Block"]
E & F --> G["Execute Finally Block (Cleanup)"]
<?php
declare(strict_types=1);
// Custom Application Exception Class
class InsufficientFundsException extends Exception {}
class BankAccount
{
public function __construct(private float $balance) {}
public function withdraw(float $amount): float
{
if ($amount <= 0) {
throw new InvalidArgumentException("Withdrawal amount must be positive.");
}
if ($amount > $this->balance) {
throw new InsufficientFundsException("Cannot withdraw $$amount. Current balance: {$this->balance}");
}
$this->balance -= $amount;
return $this->balance;
}
}
// Handling Exceptions with try...catch...finally
$account = new BankAccount(100.0);
try {
echo "Attempting Withdrawal...
";
$account->withdraw(250.0);
} catch (InsufficientFundsException $e) {
echo "Business Error: " . $e->getMessage() . "
";
} catch (InvalidArgumentException $e) {
echo "Validation Error: " . $e->getMessage() . "
";
} catch (Throwable $e) {
echo "Unexpected Fatal Error: " . $e->getMessage() . "
";
} finally {
// Always executes regardless of whether an exception occurred
echo "Transaction Log Audit Complete.
";
}
InsufficientFundsException) above generic fallback catches (Throwable).finally for Resource Cleanup: Close open file handles and database connections inside finally blocks.Throwable Silently: Never leave catch blocks empty (catch (Throwable $e) {}); log exceptions or rethrow.Create a custom exception class InvalidApiKeyException extends Exception and write code that throws it if $apiKey === ""!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.