Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

error handling - Could C++ checked exceptions be sanely implemented?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

C++ had a broken "checked" exception system.

It required compilers to do a universal catch and terminate rather than propogate the exception, and did not check that the body of the function only threw what it said it threw. It increased costs and made programs shut down.

Real checked exceptions check the body of the function to see that it only throws what it throws, and/or that code that calls it catches it or propogates the same exception checking syntax.

Now all is not lost.

There are proposals involving a unified checked exception system with C.

Here is one: https://wg21.link/p0709r2 https://github.com/cplusplus/papers/issues/310


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...