🚨 C++ Exceptions – Catch Errors, Don’t Crash
In real life, when something goes wrong, we handle it. C++ does the same using exceptions. You can throw errors and catch them before your program crashes. 🧯
This feature helps build safer and more reliable software. Instead of failing silently or crashing hard, you get a chance to fix things on the fly.
🧠 Basic Syntax
try { // Code that might cause error } catch (type e) { // Handle the error }
You use throw
to raise an exception, and catch
to handle it.
🔧 Example: Divide by Zero
#include <iostream> using namespace std; int main() { int a = 10, b = 0; try { if (b == 0) throw "Cannot divide by zero!"; cout << a / b << endl; } catch (const char* msg) { cout << "Error: " << msg << endl; } return 0; }
🛠️ Example: Throwing Different Types
#include <iostream> using namespace std; void checkAge(int age) { if (age < 18) throw age; cout << "Access granted!" << endl; } int main() { try { checkAge(15); } catch (int x) { cout << "Access denied. Age is " << x << "." << endl; } return 0; }
📝 Key Points
- try block wraps risky code.
- throw sends out the error.
- catch grabs it and handles it gracefully.
- You can catch multiple types using multiple catch blocks.
🎯 Why Use Exceptions?
- Make your program safe and stable.
- Handle unexpected errors at runtime.
- Improve user experience by avoiding crashes.
✅ Summary
- Exceptions help catch and fix errors while your program is running.
- Use
try
,throw
, andcatch
to manage unexpected situations. - Always plan for errors—better safe than sorry! 💡