example1_basic_usage_comparison.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <cassert>
#include <iostream>
#include <stdexcept>

// Function using assertion
int divideWithAssert(int a, int b) {
    assert(b != 0 && "Divisor cannot be zero");
    return a / b;
}

// Function using exception
int divideWithException(int a, int b) {
    if (b == 0) {
        throw std::invalid_argument("Divisor cannot be zero");
    }
    return a / b;
}

int main() {
    try {
        std::cout << "Assert: 10 / 2 = " << divideWithAssert(10, 2) << std::endl;
        std::cout << "Exception: 10 / 2 = " << divideWithException(10, 2) << std::endl;

        // Uncomment to see assertion failure
        // std::cout << "Assert: 10 / 0 = " << divideWithAssert(10, 0) << std::endl;

        std::cout << "Exception: 10 / 0 = " << divideWithException(10, 0) << std::endl;
    }
    catch (const std::exception& e) {
        std::cerr << "Exception caught: " << e.what() << std::endl;
    }

    return 0;
}
Back to exception_vs_assertion