Cambo Freelance
HomeServicesArticlesTutorialsTeamCoursesContact
Cambo Freelance

Professional freelance team from Cambodia delivering technology-driven solutions with cultural insight and modern expertise.

Send us a message

Ready to start your project? Get in touch with our team.

Contact Us

Services

  • Web & Mobile Development Services
  • Graphic Design & Branding Services

Useful Links

  • Home
  • Services
  • Learning
  • About Us
  • Contact
  • Pricing

© 2026 Cambo Freelance. រក្សាសិទ្ធិទាំងអស់។

TelegramFacebookLinkedInEmail
HomeTutorialsC++C++ Exception Handling
⚡C++ Tutorials

50 lessons

Beginner(21)1C++ Introduction2C++ Getting Started3C++ Syntax4C++ Output5C++ Comments6C++ Variables7C++ Data Types8C++ Constants9C++ User Input10C++ Operators11C++ Strings12C++ Math13C++ Booleans14C++ Conditions15C++ Switch16C++ Loops17C++ Break and Continue18C++ Arrays19C++ Functions20C++ References21C++ Pointers
Intermediate(19)22C++ Classes23C++ Objects24C++ Constructors25C++ Access Specifiers
Advanced(10)41C++ Smart Pointers42C++ Templates43C++ Lambda Functions44
⚡

C++ Tutorials

Lesson 31 of 50

All lessons
Beginner (21)1C++ Introduction2C++ Getting Started
26
C++ Encapsulation
27C++ Inheritance
28C++ Polymorphism
29C++ Abstraction
30C++ Files
31C++ Exception Handling
32C++ Namespaces
33C++ Structures
34C++ Enumerations
35C++ STL Introduction
36C++ Vectors
37C++ Maps
38C++ Sets
39C++ Queues
40C++ Stacks
C++ Move Semantics
45C++ Multithreading
46C++ Design Patterns
47C++ Memory Management
48C++17 Features
49C++20 Features
50C++ Performance Optimization
3
C++ Syntax
4C++ Output
5C++ Comments
6C++ Variables
7C++ Data Types
8C++ Constants
9C++ User Input
10C++ Operators
11C++ Strings
12C++ Math
13C++ Booleans
14C++ Conditions
15C++ Switch
16C++ Loops
17C++ Break and Continue
18C++ Arrays
19C++ Functions
20C++ References
21C++ Pointers
Intermediate (19)22C++ Classes23C++ Objects24C++ Constructors25C++ Access Specifiers26C++ Encapsulation27C++ Inheritance28C++ Polymorphism29C++ Abstraction30C++ Files31C++ Exception Handling32C++ Namespaces33C++ Structures34C++ Enumerations35C++ STL Introduction36C++ Vectors37C++ Maps38C++ Sets39C++ Queues40C++ Stacks
Advanced (10)41C++ Smart Pointers42C++ Templates43C++ Lambda Functions44C++ Move Semantics45C++ Multithreading46C++ Design Patterns47C++ Memory Management48C++17 Features49C++20 Features50C++ Performance Optimization
⚡C++IntermediateLesson 31 of 50CamboFreelanceJune 19, 2026

C++ Exception Handling

Master C++ exception handling with try, catch, and throw. Handle runtime errors gracefully and create custom exception classes.


Tutorials › C++ › Exception Handling
Intermediate8 min readLesson 31 of 50

What is Exception Handling?

Exceptions are runtime errors. C++ uses try, catch, and throw to handle them gracefully instead of crashing.

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

double divide(double a, double b) {
    if (b == 0) throw invalid_argument("Division by zero!");
    return a / b;
}

int main() {
    try {
        cout << divide(10, 2)  << endl;   // 5
        cout << divide(10, 0)  << endl;   // throws!
    } catch (const invalid_argument& e) {
        cout << "Error: " << e.what() << endl;
    }
    cout << "Program continues..." << endl;
    return 0;
}

Output:

5
Error: Division by zero!
Program continues...

Multiple catch Blocks

try {
    int x = -1;
    if (x < 0)  throw out_of_range("Negative value");
    if (x == 0) throw runtime_error("Zero value");
}
catch (const out_of_range& e) {
    cout << "Range error: " << e.what() << endl;
}
catch (const runtime_error& e) {
    cout << "Runtime error: " << e.what() << endl;
}
catch (...) {
    cout << "Unknown error" << endl;
}

Custom Exceptions

class InsufficientFundsException : public exception {
  public:
    const char* what() const noexcept override {
        return "Insufficient funds in account";
    }
};

void withdraw(double balance, double amount) {
    if (amount > balance) throw InsufficientFundsException();
}

try {
    withdraw(100.0, 200.0);
} catch (const InsufficientFundsException& e) {
    cout << e.what() << endl;
}

Exercise

Write a function getElement(int arr[], int size, int index) that throws out_of_range if index is invalid, and returns the element otherwise. Test with valid and invalid indices.

Show Solution
#include <iostream>
#include <stdexcept>
using namespace std;

int getElement(int arr[], int size, int index) {
    if (index < 0 || index >= size)
        throw out_of_range("Index out of bounds: " + to_string(index));
    return arr[index];
}

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    try {
        cout << getElement(arr, 5, 2)  << endl;   // 30
        cout << getElement(arr, 5, 10) << endl;   // throws
    } catch (const out_of_range& e) {
        cout << "Error: " << e.what() << endl;
    }
    return 0;
}

Quiz

  1. Which block contains code that might throw an exception?

    • A) catch
    • B> throw
    • C) try
    • D> handle
    Answer

    C) try

  2. What does catch (...) catch?

    • A) Only standard exceptions
    • B> Only runtime_error
    • C) Any exception of any type
    • D) Nothing
    Answer

    C) catch (...) is a catch-all handler for any exception type.

Summary

  • throw raises an exception; try wraps risky code; catch handles it.
  • Catch by const reference for efficiency.
  • Use catch (...) as a fallback for unknown exceptions.
  • Create custom exceptions by inheriting from std::exception.
← Previous: Files Next: Namespaces →
c++exceptionserror-handlingintermediate
PreviousLesson 30: C++ FilesNextLesson 32: C++ Namespaces
Back to All Tutorials