</>
Skip to content
C++ lessons (33/42)

C++ — Exceptions

Basic try-catch

#include <iostream>
#include <stdexcept>

int main() {
    try {
        throw std::runtime_error("Something went wrong");
    } catch (const std::exception& e) {
        std::cout << "Error: " << e.what() << std::endl;
    }
}

Custom exceptions

class InsufficientFunds : public std::exception {
    double amount;
public:
    InsufficientFunds(double a) : amount(a) {}
    const char* what() const noexcept override {
        return "Insufficient funds";
    }
    double getAmount() const { return amount; }
};

Multiple catch blocks

try {
    // code
} catch (const std::out_of_range& e) {
    std::cout << "Out of range" << std::endl;
} catch (const std::exception& e) {
    std::cout << "General: " << e.what() << std::endl;
} catch (...) {
    std::cout << "Unknown error" << std::endl;
}

Exception specifications

void safeFunction() noexcept {
    // Promise not to throw
}

void riskyFunction() {
    throw std::runtime_error("Error");
}

Mini Practice

Write C++ code that:

  1. Uses try-catch for error handling
  2. Creates a custom exception class
  3. Handles multiple exception types
  4. Uses noexcept

Up Next

In the next lesson, you'll learn about File I/O — reading and writing files.

Related Topics

Frequently Asked Questions about Exceptions

What is Exceptions in C++?

Exceptions is a fundamental concept in C++. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Exceptions?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Exceptions.

Why is Exceptions important in C++?

Exceptions is essential for C++ development. Understanding this concept will help you write better code and solve real-world problems more effectively.