🚀 EXCEPTION HANDLING IN C++
🤯 What is Exception Handling?
In C++, exceptions are runtime anomalies or unexpected errors that occur
during execution. Exception handling lets us manage these errors
gracefully instead of crashing the program.
💡 Example: Trying to divide by zero or accessing an invalid memory
location can trigger an exception!
⚡ Types of Exceptions in C++
1️. Synchronous Exceptions → Occur due to logical errors, like dividing
by zero.
2️. Asynchronous Exceptions → Happen outside the program’s control,
like disk failure or keyboard interrupts.
🔥 C++ Exception Handling: try, catch, throw
C++ provides a built-in way to handle exceptions using three keywords:
Keywor
Meaning
d
:Holds the code that might cause an
try
exception
catch 🎯 :Catches and handles exceptions
:Throws an exception when an error
throw 🚀
occurs
📌 Syntax:
try {
// Code that might throw an exception
throw SomeExceptionType("Error message");
catch(ExceptionName e1) {
// Handle the thrown exception
}
🔷 Example: try, catch, throw in action
#include <iostream>
using namespace std;
int main() {
int x = -1;
cout << "Before try block 🚀\n";
try {
cout << "Inside try block 🎯\n";
if (x < 0) {
throw x; // Throwing an exception
cout << "This will never be printed ❌\n";
catch (int x) {
cout << "Exception Caught! ⚠️\n";
cout << "After catch block ✅\n";
return 0;
🔹 Output:
Before try block 🚀
Inside try block 🎯
Exception Caught! ⚠️
After catch block ✅
🎭 Multiple Exception Handling
💡 Why do we need multiple catch blocks?
Different errors require different solutions! Instead of a one-size-fits-all
approach, we can handle each error separately for better debugging.
🔥 Syntax:
try {
// Code that may cause an exception
catch (exceptionType1 e1) {
// Handle exception of type1
catch (exceptionType2 e2) {
// Handle exception of type2
catch (...) {
// Catch-all handler (optional)
⚡ Example: Handling multiple exceptions
#include <iostream>
#include <stdexcept>
using namespace std;
void order(int choice) {
if (choice == 1) throw invalid_argument("No Pizza! 🍕❌");
if (choice == 2) throw runtime_error("Coffee Machine Error! ☕❌");
if (choice == 3) throw bad_alloc();
throw "Wrong Choice!";
}
int main() {
try {
int choice;
cout << "Order (1:Pizza 2:Coffee 3:Cake): ";
cin >> choice;
order(choice);
catch (const invalid_argument &e) { cout << "Error: " << e.what() <<
endl; }
catch (const runtime_error &e) { cout << "Error: " << e.what() <<
endl; }
catch (const bad_alloc &) { cout << "Error: No Cake! 🎂❌" << endl; }
catch (...) { cout << "Unknown Error! ❓" << endl; }
return 0;
🎯 C++: throw vs throws (Java)
throw 🚀 → Used in C++ to throw exceptions
throws ❌ → Used in Java, not in C++
noexcept → Used in C++ to indicate a function won’t throw
exceptions
💰 Example: Throwing an Exception
#include <iostream>
using namespace std;
void withdrawMoney(int balance, int amount) {
if (amount > balance) {
throw "Not enough money! 🏦❌ Sell a kidney or try again later. 😂";
cout << "Withdrawal successful! ✅ Remaining balance: " << balance -
amount << endl;
int main() {
try {
withdrawMoney(1000, 5000);
} catch (const char* msg) {
cout << "Error: " << msg << endl;
return 0;
🎭 Catch All Exceptions: catch(...)
When you can’t predict all possible errors, catch-all handlers step in to
save the day!
catch(...) {
// Handles ANY exception
⚡ Example: Catch All in Action
#include <iostream>
using namespace std;
int main() {
int num;
cout << "\n Enter a number (-1, 0, 1): ";
cin >> num;
try {
if (num == 0)
throw "Zero"; // Exception 1: const char*
else if (num == -1)
throw num; // Exception 2: int
else if (num == 1)
cout << "\n NUMBER " << num;
else
throw (float) num; // Exception 3: float
catch (int num) { cout << "\n" << num << " is negative"; }
catch (char* msg) { cout << "\n The number is " << msg; }
catch (...) { cout << "\n No specific code executed"; }
cout << "\n EXITING MAIN()\n";
return 0;
🛠 User-Defined Exceptions (Custom Exceptions)
C++ lets us create custom exceptions by inheriting from
std::exception.
🤖 Example: Robot Battery Warning
#include <iostream>
#include <exception>
using namespace std;
class BatteryLowException : public exception {
public:
const char* what() const noexcept {
return "⚡ Battery critically low! Robot is going to sleep... 🤖💤";
};
void checkBattery(int battery) {
if (battery < 10) {
throw BatteryLowException();
cout << "🔋 Battery level sufficient! Keep going, Robot! 🤖" << endl;
int main() {
try {
checkBattery(5);
} catch (const BatteryLowException& e) {
cout << "Exception: " << e.what() << endl;
return 0;
🤔 Why Use Exception Handling in C++?
🔹 Traditional Error Handling
❌ Uses if-else, making code messy and hard to maintain.
🔹 Exception Handling (try/catch)
✅ Separates error handling from normal code for cleaner and more
readable programs!
📌 Advantages:
✔️No messy error codes – Just throw exceptions when things go wrong!
✔️Functions handle only relevant exceptions – Others can be passed
to the caller.
✔️Grouping of errors – Related exceptions can be categorized in
classes.
🎯 Final Takeaway
👉 Exception handling makes your C++ programs more robust and
readable.
👉 Always use try-catch blocks to prevent unexpected crashes.
👉 Custom exceptions make debugging easier!
🔥 Now go write some C++ with confidence! 🚀💻