Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Exception Handling: Catching Errors

Lesson 37 of 53 in the free Foundation of C & C++ notes on Siksha Sarovar, written by Rohit Jangra.

Handling the Unexpected

In old-school C, if you divided by zero or ran out of memory, your program simply crashed with no explanation. C++ provides a structured way to gracefully catch and recover from errors using Exceptions.

The Three Key Keywords

  1. try: Wrap the block of code that might fail.
  2. throw: Manually trigger an error "signal" if something goes wrong.
  3. catch: Handle the signal and prevent the crash.
try {
    if (age < 18) throw 505; // Throw an error code
} catch (int errorCode) {
    cout << "Access denied. Error: " << errorCode;
}

The Standard Library Exceptions (<stdexcept>)

C++ has a built-in hierarchy of common error types:

  • out_of_range: You tried to access index 10 of a 5-item array.
  • invalid_argument: You passed bad data to a function.
  • bad_alloc: The computer is completely out of memory.

Why use Exceptions?

They allow you to separate your "Normal Logic" from your "Error Handling Logic." This makes your code much cleaner and easier to read. Instead of checking if(error) after every single line, you just wrap the whole process in one try block.

The "Catch-All" Block

catch (...) {
    cout << "An unknown disaster occurred!";
}
Never let an exception escape from a Destructor. If an exception is thrown while the system is already cleaning up after another exception, C++ will instantly kill your program with no chance for recovery.