Will such a statement be used?

Can I put just one all-encompassing try-catch statement in my main function that covers the entire program? Or do all functions require their own? What I mean is, will something like this work:

int main(){
    try{
        foo();
        bar();
    };

    catch(char* e){
        //Do stuff with e
    };
};

void foo(){throw "You'll never reach the bar.";};
void bar(){throw "Told you so.";};

If not, is there a similar way this can be done?

Can I put just one all-encompassing try-catch statement in my main function that covers the entire program?

Yes. catch (...)
catches everything.

#include 

int main()
{
    try
    {
        // do something
    }
    catch (...)
    {
        std::cerr << "exception caughtn";
    }
}
Or do all functions require their own?

No. That would defeat the whole purpose of exceptions.

catch(char* e){
    //Do stuff with e
};

This code is a result of the misunderstanding that exceptions are error messages. Exceptions are not error messages.
Exceptions in C++ can be of any type. This includes char*
, of course, but it is completely unidiomatic.

What you really want to do is catch std::exception
, which includes
an error message, accessible via the what()
member function. Well-written C++ code only throws exceptions of type std::exception
or derived classes. You can add ...
as a fallback for all other cases:

#include 
 #include 

int main()
{
    try
    {
        // do something
    }
    catch (std::exception const& exc)
    {
        std::cerr << exc.what() << "n";
    }
    catch (...)
    {
        std::cerr << "unknown exception caughtn";
    }
}
throw "You'll never reach the bar.";

Consequently, throwing char arrays is wrong. It’s wrong on a technical level if you expect a char const[]
to be converted to a char*
, but it’s especially wrong on a design level. Replace the array with a dedicated exception type like
std::runtime_error

:

throw std::runtime_error("You'll never reach the bar.");
Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Will such a statement be used&quest;

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录