How do I avoid exceptions and handle errors std::expected (when available) in C++?

C++, std::expected, error handling, exceptions, C++20, programming, software development
Learn how to handle errors gracefully in C++ without using exceptions by leveraging std::expected for better control flow and error management.

#include <iostream>
#include <expected> // Requires C++20

// Function that simulates an operation that can fail
std::expected performOperation(int value) {
    if (value < 0) {
        return std::unexpected("Negative value error");
    }
    // Perform some calculations and return success
    return value * 10;
}

int main() {
    // Example of using std::expected for error handling
    auto result = performOperation(-5);

    if (result) {
        std::cout << "Operation succeeded with result: " << *result << std::endl;
    } else {
        std::cout << "Operation failed: " << result.error() << std::endl;
    }

    return 0;
}
    

C++ std::expected error handling exceptions C++20 programming software development