PHP Exception Handling – Try, Catch & Throw Explained 🚀
Imagine PHP as a tightrope walker 🎪. When things go wrong (errors happen), instead of crashing down, PHP can use a try-catch safety net to handle the issue gracefully! 🤹♂️
PHP provides try
, catch
, and throw
to deal with **exceptions** (unexpected problems) without breaking your entire application.
🔹 What is an Exception?
An exception is a special kind of error that can be caught and handled instead of stopping the script.
📝 Basic Example: Try & Catch
Let’s wrap a potentially risky operation inside try
and handle errors using catch
.
<?php try { echo 10 / 0; // Division by zero causes an error } catch (Exception $e) { echo "Oops! Something went wrong: " . $e->getMessage(); } ?>
Oops! 🤦♂️ PHP doesn’t like dividing by zero, but our catch
block prevents a crash.
🔹 Using throw
to Create Custom Exceptions
You can manually trigger (throw) exceptions using throw
.
📝 Example: Throwing an Exception
<?php function checkAge($age) { if ($age < 18) { throw new Exception("Access Denied: You must be 18+."); } return "Welcome!"; } try { echo checkAge(16); } catch (Exception $e) { echo "Error: " . $e->getMessage(); } ?>
Result: This throws an error if the age is less than 18.
🔹 Catching Multiple Exceptions
You can handle different types of exceptions separately.
📝 Example: Handling Different Exceptions
<?php try { throw new Exception("General Error!"); } catch (InvalidArgumentException $e) { echo "Invalid Argument: " . $e->getMessage(); } catch (Exception $e) { echo "Caught Exception: " . $e->getMessage(); } ?>
Tip: The catch
blocks should go from most specific to least specific.
🔹 Using finally
(Always Execute Code)
The finally
block runs no matter what—whether an exception occurs or not.
📝 Example: Try, Catch & Finally
<?php try { echo "Trying... <br>"; throw new Exception("An error occurred!"); } catch (Exception $e) { echo "Caught: " . $e->getMessage() . "<br>"; } finally { echo "This always runs! ✅"; } ?>
Result: The finally
block ensures some code always runs.
🎯 Key Takeaways
try
→ Wraps risky code.catch
→ Handles exceptions.throw
→ Manually triggers an exception.finally
→ Always executes, no matter what.
📝 Practice Time!
Try throwing your own exceptions and handling them differently! Can you throw an exception if a username is empty? 🤔