Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🔴 Advanced  ·  Lesson 52

Exception Handling in C++

In this lesson: Handle errors in C++ with try, catch and throw — standard exceptions and custom ones — with output. In Hindi & English.

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.
← 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.
Next topicStandard Template Library (STL) Your progress: 52 / 81 (64%) · Lesson 53 / 81 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free