PHP menangani error dengan exception yang ditangkap melalui try/catch/finally. Penanganan exception yang tepat berarti menangkap tipe-tipe spesifik, membuat custom exception yang bermakna, membersihkan resource, dan tidak pernah mengekspos detail internal kepada pengguna.
Struktur dasar
<?php
try {
$data = riskyOperation();
} catch (InvalidArgumentException $e) { // catch a SPECIFIC type first
handleBadInput($e->getMessage());
} catch (DatabaseException $e) {
handleDbError($e);
} catch (Throwable $e) { // catch-all (Error OR Exception) — last
logError($e);
throw $e; // re-throw what you can't handle
} finally {
cleanup(); // ALWAYS runs (success or failure)
}
Tangkap tipe exception yang spesifik (yang paling spesifik terlebih dahulu), gunakan Throwable sebagai catch-all final (mencakup both Error dan Exception), dan gunakan finally untuk cleanup yang harus selalu berjalan.
Throwing dan custom exception
// throwing
if ($amount < 0) {
throw new InvalidArgumentException("Amount must be positive, got $amount");
}
// a custom exception for your domain
class InsufficientFundsException extends Exception {
public function __construct(private float $shortfall) {
parent::__construct("Short by $shortfall");
}
public function getShortfall(): float { return $this->shortfall; }
}
throw new InsufficientFundsException(50.0);
Kelas custom exception membuat error handling lebih ekspresif dan memungkinkan caller menangkap domain error spesifik.
Exception chaining (pertahankan cause)
try {
$db->query(...);
} catch (PDOException $e) {
// wrap with context, preserving the original as the "previous" exception
throw new RepositoryException("Failed to load user", 0, $e);
}
Argumen konstruktor ketiga melakukan chain original exception ($e->getPrevious()), mempertahankan full cause untuk debugging.
Best practices
✓ Catch SPECIFIC exceptions, not a blanket Throwable (unless intentionally last)
✓ Don't swallow exceptions silently (empty catch) — log or re-throw
✓ Use finally / proper cleanup for resources (files, connections)
✓ Create meaningful custom exceptions for domain errors
✓ SECURITY: log details internally; show users a generic message (don't leak
stack traces / internal info — display_errors off in production)
Mengapa ini penting
Penanganan exception yang tepat sangat penting untuk membangun aplikasi PHP yang robust, reliable, dan secure.
Memahami struktur try/catch/finally, menangkap tipe exception spesifik (untuk targeted handling) dengan Throwable sebagai final catch-all (mencakup both Error dan Exception di PHP modern), dan menggunakan finally untuk guaranteed cleanup adalah pengetahuan dasar sehari-hari.
Di luar mekanika, best practices sangat penting: membuat meaningful custom exception untuk domain error membuat kode lebih ekspresif dan memungkinkan caller menangani failure spesifik; exception chaining mempertahankan root cause untuk debugging; dan yang sangat penting, tidak menghilangkan exception diam-diam (logging atau re-throwing instead) mencegah hidden failure.
Poin yang sangat penting adalah security: exception dan error harus di-log secara internal tetapi tidak pernah diekspos ke user (stack trace dan detail internal bocor informasi sensitif dan membantu attacker — hence display_errors off di production).
Mengetahui cara menangani exception dengan benar — specific catch, custom exception, cleanup, chaining, dan secure logging daripada exposure — membedakan robust, professional PHP dari kode fragile yang crash tidak graceful atau leak information, menjadikannya pengetahuan penting untuk membangun aplikasi yang reliable dan secure.
