Exception Handling
Written and reviewed by Gagan Bhardwaj · Senior IT Faculty · 15+ years’ experience
What is exception handling?
Exception handling is how C++ deals with run-time errors without crashing. Instead of checking return codes everywhere, you put risky code in a try block, throw an error when something goes wrong, and catch it in a handler. Normal logic and error logic stay cleanly separated.
try, throw and catch
#include <iostream>
using namespace std;
double divide(int a, int b) {
if (b == 0) throw "Division by zero!"; // throw
return (double)a / b;
}
int main() {
try {
cout << divide(10, 2) << "\n";
cout << divide(5, 0) << "\n"; // throws
}
catch (const char *msg) { // catch
cout << "Error: " << msg << "\n";
}
return 0;
}5
Error: Division by zero!
When throw runs, control jumps straight to the matching catch.
Catching multiple types
Add several catch blocks, most specific first:
try {
// ...
}
catch (int e) { cout << "int error " << e; }
catch (const char *e) { cout << "text error " << e; }Standard exceptions
The standard library throws types derived from std::exception, with a what() message. Catch by reference:
#include <stdexcept>
try {
throw runtime_error("something failed");
}
catch (const exception &e) {
cout << e.what(); // "something failed"
}Catch-all handler
catch (...) catches anything — a safety net, though it gives no detail:
catch (...) {
cout << "Some unknown error occurred";
}Best practices
- Throw by value, catch by
constreference. - Prefer standard exception types (or ones derived from
std::exception). - Order handlers specific → general; put
catch (...)last. - Use RAII / smart pointers so resources free even when an exception unwinds the stack.
Common mistakes
- Putting a general handler before a specific one (it swallows everything).
- Catching by value and slicing the exception object.
- Leaking resources because cleanup was skipped by the throw (use RAII).
- Using exceptions for ordinary control flow instead of real errors.
Write a function that throws std::out_of_range if an index is invalid, and a std::invalid_argument for negative input. Call it inside a try with separate catch blocks and a final catch (...).
Summary
- Exception handling manages run-time errors without crashing.
trywraps risky code,throwraises,catchhandles.- Use multiple catches, most specific first.
std::exceptionandwhat()give a uniform interface.- Throw by value, catch by reference, and rely on RAII for cleanup.
Frequently Asked Questions
What is exception handling in C++?
try block, an error is signalled with throw, and a matching catch block handles it instead of letting the program crash.What are try, catch, and throw in C++?
try wraps code that might throw an error; throw raises an exception when something goes wrong; and catch receives an exception of a matching type and handles it. Together they let a program respond to errors instead of terminating abruptly.How do you catch multiple exception types in C++?
catch blocks after one try, each for a different exception type, and the first matching one runs. Order them from most specific to most general, since a broad handler placed first would catch everything before the specific ones get a chance.What is std::exception in C++?
std::exception is the base class for the standard library's exception types, such as std::runtime_error and std::out_of_range. Catching it by reference lets you handle many related errors uniformly and read a message through its what() member function.What is a catch-all handler in C++?
catch (...), catches any exception regardless of its type. It is useful as a last resort to prevent a crash, but because it gives no information about the error, more specific catch blocks should handle known cases first.Exception handling क्या है?
Exception handling वह तरीका है जिससे C++ run-time errors को crash हुए बिना संभालता है। हर जगह return codes जाँचने के बजाय, आप जोखिम भरा code try block में रखते हैं, कुछ गलत होने पर error throw करते हैं, और इसे handler में catch करते हैं। सामान्य logic और error logic साफ़ अलग रहते हैं।
try, throw और catch
#include <iostream>
using namespace std;
double divide(int a, int b) {
if (b == 0) throw "Division by zero!"; // throw
return (double)a / b;
}
int main() {
try {
cout << divide(10, 2) << "\n";
cout << divide(5, 0) << "\n"; // throw karta hai
}
catch (const char *msg) { // catch
cout << "Error: " << msg << "\n";
}
return 0;
}5
Error: Division by zero!
जब throw चलता है, नियंत्रण सीधे मेल खाते catch पर कूदता है।
कई types catch करना
कई catch blocks जोड़ें, सबसे विशिष्ट पहले:
try {
// ...
}
catch (int e) { cout << "int error " << e; }
catch (const char *e) { cout << "text error " << e; }Standard exceptions
Standard library std::exception से derived types throw करती है, एक what() message के साथ। Reference से catch करें:
#include <stdexcept>
try {
throw runtime_error("something failed");
}
catch (const exception &e) {
cout << e.what(); // "something failed"
}Catch-all handler
catch (...) कुछ भी catch करता है — एक safety net, हालाँकि यह कोई विवरण नहीं देता:
catch (...) {
cout << "Some unknown error occurred";
}सर्वोत्तम अभ्यास
- Value से throw करें,
constreference से catch करें। - Standard exception types पसंद करें (या
std::exceptionसे derived)। - Handlers विशिष्ट → सामान्य क्रमबद्ध करें;
catch (...)अंत में रखें। - RAII / smart pointers इस्तेमाल करें ताकि exception से stack unwind होने पर भी resources मुक्त हों।
आम गलतियाँ
- विशिष्ट से पहले सामान्य handler रखना (यह सब निगल लेता है)।
- Value से catch करके exception object slice करना।
- Throw द्वारा cleanup छूट जाने से resources leak करना (RAII इस्तेमाल करें)।
- असली errors के बजाय सामान्य control flow के लिए exceptions इस्तेमाल करना।
एक function लिखें जो index अमान्य होने पर std::out_of_range, और ऋणात्मक input के लिए std::invalid_argument throw करे। इसे अलग catch blocks और एक अंतिम catch (...) वाले try के अंदर call करें।
सारांश
- Exception handling run-time errors को crash हुए बिना प्रबंधित करता है।
tryजोखिम भरा code घेरता है,throwउठाता है,catchसंभालता है।- कई catches इस्तेमाल करें, सबसे विशिष्ट पहले।
std::exceptionऔरwhat()एक समान interface देते हैं।- Value से throw, reference से catch, और cleanup के लिए RAII पर निर्भर रहें।