Free tutorials & notes in Hindi & English · Clean code examples · Mobile friendly learning
🔴 Advanced  ·  Lesson 52

Exception Handling

Written and reviewed by · 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

C++
#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;
}
Output:
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:

C++
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:

C++
#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:

C++
catch (...) {
    cout << "Some unknown error occurred";
}

Best practices

  • Throw by value, catch by const reference.
  • 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.
🏋️ Practice

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.
  • try wraps risky code, throw raises, catch handles.
  • Use multiple catches, most specific first.
  • std::exception and what() 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++?
Exception handling is a way to deal with run-time errors cleanly, separating error-handling code from normal logic. Code that might fail goes in a 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++?
You write several 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++?
A catch-all handler, written 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

C++
#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;
}
Output:
5
Error: Division by zero!

जब throw चलता है, नियंत्रण सीधे मेल खाते catch पर कूदता है।

कई types catch करना

कई catch blocks जोड़ें, सबसे विशिष्ट पहले:

C++
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 करें:

C++
#include <stdexcept>
try {
    throw runtime_error("something failed");
}
catch (const exception &e) {
    cout << e.what();      // "something failed"
}

Catch-all handler

catch (...) कुछ भी catch करता है — एक safety net, हालाँकि यह कोई विवरण नहीं देता:

C++
catch (...) {
    cout << "Some unknown error occurred";
}

सर्वोत्तम अभ्यास

  • Value से throw करें, const reference से 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 पर निर्भर रहें।
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.