exception handling in C++ --- TEAM AKASH
exception handling in C++ --- TEAM AKASH
Keywor
Meaning
d
📌 Syntax:
try {
catch(ExceptionName e1) {
#include <iostream>
int main() {
int x = -1;
try {
if (x < 0) {
catch (int x) {
return 0;
🔹 Output:
Exception Caught! ⚠️
After catch block ✅
🔥 Syntax:
try {
catch (...) {
#include <iostream>
#include <stdexcept>
int main() {
try {
int 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; }
return 0;
#include <iostream>
throw "Not enough money! 🏦❌ Sell a kidney or try again later. 😂";
int main() {
try {
withdrawMoney(1000, 5000);
return 0;
When you can’t predict all possible errors, catch-all handlers step in to
save the day!
catch(...) {
#include <iostream>
int main() {
int num;
cout << "\n Enter a number (-1, 0, 1): ";
try {
if (num == 0)
else if (num == 1)
else
catch (int num) { cout << "\n" << num << " is negative"; }
catch (char* msg) { cout << "\n The number is " << msg; }
return 0;
#include <iostream>
#include <exception>
public:
};
throw BatteryLowException();
cout << "🔋 Battery level sufficient! Keep going, Robot! 🤖" << endl;
int main() {
try {
checkBattery(5);
return 0;
✔️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