C++里边有个看着比较怪异的语法,叫做“function-try-block”。见下面代码示例中的普通函数和构造函数的用法。另外析构函数也支持这种用法。
个人不觉得这个用法很赞,主要是因为它的行为比较复杂,对于普通函数和构造函数析构函数在到达catch-block结尾时候的行为不太一致,可以认为是比较坑猿的。
另外这个特性在C++98的时候就已经存在了,所以示例代码特意没有使用C++11或更高版本的语法。
#include#include // Demonstration of function-try-block // See Also: // https://en.cppreference.com/w/cpp/language/function-try-block class SomeException : public std::exception { private: std::string message; public: SomeException (const char * msg) : message(msg) { } virtual ~SomeException() _NOEXCEPT { } virtual const char* what() const _NOEXCEPT { return message.c_str(); } }; void foo () { std::cout << "simple foo function" << std::endl; } void bar() { std::cout << "evil bar function" << std::endl; throw SomeException("Some exception in bar"); } void tryfunction (int i=0) try { foo(); bar(); } catch(const std::exception & e) { std::cout << "something was wrong - " << e.what() << std::endl; std::cout << "i = " << i << std::endl; } class EvilBase { public: EvilBase () { throw SomeException("dark side of the force"); } virtual ~EvilBase () { } }; class InnocentDerived : public EvilBase { public: InnocentDerived() try : EvilBase(), m(1) { // other initializations } catch (const std::exception & e) { std::cerr << "what is the problem? " << e.what() << std::endl; } // the current exception is rethrown here private: int m; }; int main() { tryfunction(); InnocentDerived d; }
讲代码保存为文件tryfunction.cpp,编译命令如下:
`$ g++ -std=c++98 tryfunction.cpp -o ./a1`



