0% found this document useful (0 votes)
5 views1 page

Handling Optional Values in C++

Uploaded by

poojashetty9801
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views1 page

Handling Optional Values in C++

Uploaded by

poojashetty9801
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

// opt_throw_test.

cpp
#include <optional>
#include <stdexcept>
#include <iostream>

std::optional<int> compute(int x) {
if (x < 0) {
throw std::runtime_error("negative input"); // <-- forbidden
}
return x * 2;
}

int main() {
auto r = compute(-5);
if (r) std::cout << *r << "\n";
else std::cout << "no result\n";
return 0;
}

You might also like