Exception handling is a powerful mechanism in C++ to handle runtime errors gracefully, preventing your program from crashing unexpectedly. Instead of abrupt termination (like segmentation fault or divide by zero), you can detect errors, handle them, and continue or exit cleanly.

This topic builds perfectly on previous ones (Types of Errors → Runtime Errors → Debugging). Exception handling helps manage runtime errors professionally.

Why Exception Handling? (For All Levels)

Problems Without Exception Handling

  • Program crashes on errors (e.g., divide by zero, file not found).
  • Hard to recover or show user-friendly messages.

Benefits

  • Clean separation: Normal code vs error-handling code.
  • Program can recover or exit safely.
  • User gets meaningful messages instead of crashes.
  • Essential in real-world applications (games, banking software, student record systems).

Example Scenario (Student Record System)

If user enters negative marks or tries to divide total by zero students → crash! With exceptions → show “Invalid marks!” and continue.

Basic Syntax: try, catch, throw

The Three Keywords

  • throw: Throws (raises) an exception when an error occurs.
  • try: Block of code that might cause an exception.
  • catch: Block that handles the thrown exception.

Basic Structure

C++
 
#include <iostream>
using namespace std;

int main() {
    try {
        // Code that might throw an exception
        int age;
        cout << "Enter age: ";
        cin >> age;
        
        if (age < 0) {
            throw "Age cannot be negative!";  // Throw exception
        }
        
        cout << "Age is: " << age << endl;
    }
    catch (const char* msg) {  // Catch the exception
        cout << "Error: " << msg << endl;
    }
    
    cout << "Program continues normally..." << endl;
    return 0;
}
 
 

Output if age = -5:

text
 
Error: Age cannot be negative!
Program continues normally...
 
 

How It Works – Step by Step (For Class 8–12)

  1. Program executes code inside try block.
  2. If no error → catch is skipped.
  3. If error detected → throw sends an exception object.
  4. Control jumps immediately to matching catch block.
  5. After catch executes → program continues normally (no crash!).

What Can You Throw?

You can throw almost anything:

  • int, float, char
  • string
  • const char* (C-style string)
  • Custom objects (advanced)

Examples of throw

C++
 
throw 404;                    // int
throw "File not found";       // const char*
throw string("Invalid input"); // string
throw -1.5;                   // double
 
 

Multiple catch Blocks (Handling Different Errors)

One try can have multiple catch blocks for different exception types.

C++
 
try {
    int num, den;
    cout << "Enter numerator and denominator: ";
    cin >> num >> den;
    
    if (den == 0) {
        throw 0;  // Throw int for divide by zero
    }
    if (num < 0 || den < 0) {
        throw "Negative values not allowed!";  // Throw string
    }
    
    cout << "Result: " << num / den << endl;
}
catch (int errorCode) {
    if (errorCode == 0)
        cout << "Error: Division by zero!" << endl;
}
catch (const char* msg) {
    cout << "Error: " << msg << endl;
}
catch (...) {  // Catch-all (explained later)
    cout << "Unknown error occurred!" << endl;
}
 
 

Order matters: Specific catches first, general last.

Built-in Exception Classes (For Class 11–12 & BS)

C++ provides standard exceptions in <stdexcept> header.

Common ones:

  • std::out_of_range
  • std::invalid_argument
  • std::runtime_error
  • std::overflow_error
  • std::logic_error

Example with Standard Exceptions

C++
 
#include <iostream>
#include <stdexcept>
using namespace std;

int main() {
    try {
        int marks;
        cout << "Enter marks (0-100): ";
        cin >> marks;
        
        if (marks < 0 || marks > 100) {
            throw invalid_argument("Marks must be between 0 and 100");
        }
        
        cout << "Valid marks: " << marks << endl;
    }
    catch (const invalid_argument& e) {
        cout << "Invalid Argument Error: " << e.what() << endl;
    }
    
    return 0;
}
 
 

.what() returns the error message.

Catch-All Handler ( … )

Catches any type of exception – useful as a safety net.

C++
 
try {
    // risky code
}
catch (const invalid_argument& e) {
    cout << e.what() << endl;
}
catch (...) {  // Must be last
    cout << "Some unknown error occurred. Contact support." << endl;
}
 
 

Best Practice: Always have a catch-all at the end.

Exception in Functions

Exceptions can propagate up the call stack.

C++
 
void divide(int a, int b) {
    if (b == 0) {
        throw "Division by zero!";
    }
    cout << a / b << endl;
}

int main() {
    try {
        divide(10, 0);
    }
    catch (const char* msg) {
        cout << "Caught: " << msg << endl;
    }
    return 0;
}
 
 

Exception thrown in divide() is caught in main().

Real-World Example: Enhanced Student Record System

Add exception handling to prevent crashes.

C++
 
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;

void validateMarks(float marks) {
    if (marks < 0 || marks > 100) {
        throw invalid_argument("Marks must be between 0 and 100");
    }
}

void validateAge(int age) {
    if (age < 5 || age > 20) {
        throw out_of_range("Age must be between 5 and 20 for school");
    }
}

int main() {
    try {
        int age;
        float marks;
        
        cout << "Enter age: ";
        cin >> age;
        validateAge(age);
        
        cout << "Enter marks: ";
        cin >> marks;
        validateMarks(marks);
        
        cout << "Student data valid!" << endl;
    }
    catch (const invalid_argument& e) {
        cout << "Input Error: " << e.what() << endl;
    }
    catch (const out_of_range& e) {
        cout << "Range Error: " << e.what() << endl;
    }
    catch (...) {
        cout << "Unexpected error!" << endl;
    }
    
    cout << "Program ends safely." << endl;
    return 0;
}
 
 

Advanced Topics (BS Level)

Creating Custom Exception Classes

C++
 
class NegativeMarksException : public runtime_error {
public:
    NegativeMarksException()
        : runtime_error("Marks cannot be negative") {}
};

void checkMarks(float m) {
    if (m < 0) throw NegativeMarksException();
}
 
 

Exception Safety

  • Basic: No leaks if exception thrown.
  • Strong: Program state unchanged.
  • Use RAII (Resource Acquisition Is Initialization) – smart pointers, destructors.

noexcept Keyword (C++11+)

Tell compiler function won’t throw:

C++
 
void safeFunction() noexcept {
    // No throw allowed
}
 
 

When NOT to Use Exceptions

  • In performance-critical code (games, embedded).
  • For expected errors (use return codes instead).

Summary Table (For Your Website)

 
 
KeywordPurposeExample
throwRaise an exceptionthrow “Error!”;
tryMonitor code for exceptionstry { risky code }
catchHandle specific or all exceptionscatch(int e) { … }
catch(…)Catch any exceptionSafety net