Everyone seems to hate the idea - and I've been recommended to use sum_types instead.
However, C++ has some "deprecated" throws(...)
syntax
With this:
template<class Ret, class... E>
struct checked {
bool threw();
Ret get();
std::variant<std::unique_ptr<E>...> exception();
}
One could write
int throwing() throws std::invalid_argument, std::runtime_error;
try {
auto x = 1 + throwing();
} catch(const std::runtime_error& e){
printlin("threw runtime error: {}", e.what());
} catch(const std::invalid_argument& e){
printlin("threw invalid argument: {}", e.what());
}
which would compile to
checked<int, std::variant<std::invalid_argument, std::runtime_error>> throwing();
auto result = throwing();
if (result.threw()) {
auto exception = result.exception();
switch(exception.index()){
case 0:
printlin("threw invalid argument: {}", exception.get(0)->what()); break;
case 1:
printlin("threw runtime error: {}", exception.get(1)->what());
}
} else {
auto x = 1 + reuslt.get();
}
allows for propagated checked exceptions - while still allowing one to use their beloved sum type
Could this be implemented in c++ - and would this be faster than current exceptions
question from:
https://stackoverflow.com/questions/66055363/could-c-checked-exceptions-be-sanely-implemented 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…