Will such a statement be used?

综合编程 2017-12-30

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!

责编内容by:Hello, buddy! (源链)。感谢您的支持!

您可能感兴趣的

__ 场景 macOS 处理时间函数有自己的 NSDate, C 的库函数 time.h相比它就有点弱了, 不过麻雀虽小, 五脏俱全. 麻烦的是在处理一些 UTC,GMT之类的转换时需要自己动...
Python3 与 C# 面向对象之~继承与多态 在OOP中,当我们定义一个Class的时候,可以从某个现有的Class继承 新的Class称为子类,而被继承的class称为 基类 或者 父类 Python的继承格式 ==> x...
Choosing a node.js library with pure js vs C++ add... Assuming that the libraries are functionally similar, I can think of a couple pros and cons: C+...
Want to modernize your C++ codebase, check first t... The refactoring is defined as the process of changing a software system in such a way that it does n...
Hacking extern(C++) Classes to Work in betterC First up, here’s a big disclaimer if the title didn’t warn you enough: this is a hack. It’s just...