When is a function try block useful?

后端 未结 6 1510
忘了有多久
忘了有多久 2020-11-30 06:31

I\'m wondering when programmers use function try blocks. When is it useful?

void f(int i)
try
{
   if ( i  < 0 ) 
      throw \"less than zero\";
   std::         


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 06:53

    Another thing you can use them for is to provide extra data during debugging, in a manner that doesn't interfere with the finished build. I haven't seen anyone else use or advocate it, but it's something I find convenient.

    // Function signature helper.
    #if defined(_WIN32) || defined(_WIN64)
        #define FUNC_SIG __FUNCSIG__
    #elif defined(__unix__)
        #define FUNC_SIG __PRETTY_FUNCTION__
    // Add other compiler equivalents here.
    #endif  /* Function signature helper. */
    
    void foo(/* whatever */)
    #ifdef     DEBUG
    try
    #endif  /* DEBUG */
    {
        // ...
    }
    #ifdef     DEBUG
    catch(SomeExceptionOrOther& e) {
        std::cout << "Exception " << e.what() << std::endl
                  << "* In function: " << FUNC_SIG << std::endl
                  << "* With parameters: " << /* output parameters */ << std::endl
                  << "* With internal variables: " << /* output vars */ << std::endl;
    
        throw;
    }
    #endif  /* DEBUG */
    

    This would allow you to both obtain useful information while testing your code, and easily dummy it out without affecting anything.

提交回复
热议问题