Try-Catch Exception
<?php
try {
$file = fopen("tidak_ada.txt", "r");
if (!$file) {
throw new Exception("File tidak ditemukan");
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
} finally {
echo "Selesai";
}
?>
Custom Exception
<?php
class InvalidAgeException extends Exception {
public function __construct($message = "", $code = 0) {
parent::__construct($message, $code);
}
}
try {
$age = 15;
if ($age < 18) {
throw new InvalidAgeException("Usia tidak valid");
}
} catch (InvalidAgeException $e) {
echo "Custom Error: " . $e->getMessage();
}
?>
Error Reporting
<?php
// Set error reporting level
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Log errors to file
ini_set('log_errors', 1);
ini_set('error_log', '/path/to/error.log');
// Custom error handler
function myErrorHandler($errno, $errstr) {
echo "Error: " . $errstr;
}
set_error_handler("myErrorHandler");
?>
Multiple Catch Blocks
<?php
try {
// Code yang mungkin error
} catch (TypeError $e) {
echo "Type Error: " . $e->getMessage();
} catch (DivisionByZeroError $e) {
echo "Division Error: " . $e->getMessage();
} catch (Exception $e) {
echo "General Error: " . $e->getMessage();
}
?>
Tips: Error handling yang baik membuat aplikasi lebih robust dan mudah di-debug. Selalu gunakan try-catch untuk operasi yang berisiko.