JavaScript Error Handling: try...catch
Error handling in JavaScript helps prevent scripts from crashing when unexpected issues arise. The try...catch
statement allows you to handle errors gracefully.
🔹 Basic try...catch
Syntax
✔️ The try
block runs the code and checks for errors.
✔️ The catch
block runs if an error occurs.
🔹 Example: Handling Errors Gracefully
✔️ No error occurs, so the catch
block is skipped.
Handling an Actual Error
✅ Output:
✔️ The script doesn’t crash, and we get an error message instead.
🔹 Using finally
for Cleanup
The finally
block always runs, whether an error occurs or not.
✅ Output:
✔️ Use finally
to release resources (e.g., close files, stop a loader).
🔹 Throwing Custom Errors
You can manually throw errors using throw
.
✅ Output:
✔️ throw
let's you define custom error messages.
🔹 Handling Specific Errors with instanceof
Different errors can be handled individually.
✅ Output:
✔️ This is useful when handling different error types.
🔹 Summary
✅ try
→ Runs the code that might fail
✅ catch
→ Handles errors if they occur
✅ finally
→ Runs cleanup code, no matter what
✅ throw
→ Manually generate errors
✅ instanceof
→ Handle specific error types
🚀 Need more examples? Let me know! 😊