PHP Exceptions
Exceptions are used for error handling.
Instead of crashing applications, we can safely catch errors.
try
try {
}
catch
catch (
Exception $e
) {
}
Example
try {
throw new Exception(
"Database Failed"
);
}
catch (
Exception $e
) {
echo
$e->getMessage();
}
finally
finally {
}
Always executes.
Custom Exceptions
class DatabaseException
extends Exception {
}
Throwing
throw new DatabaseException(
"Failed"
);
PocketMine Example
try {
$this->saveData();
}
catch (
Throwable $e
) {
$this->getLogger()
->error(
$e->getMessage()
);
}
Throwable Hierarchy
Throwable
├── Exception
└── Error
Best Practices
✅ Catch specific exceptions.
✅ Log errors.
✅ Never hide exceptions silently.
Next Chapter
➡ Namespaces