Call-stack for exceptions in C++

后端 未结 10 1382
忘了有多久
忘了有多久 2020-12-14 15:33

Today, in my C++ multi-platform code, I have a try-catch around every function. In every catch block I add the current function\'s name to the exception and throw it again,

10条回答
  •  一整个雨季
    2020-12-14 16:05

    An exception that isn't handled is left for the calling function to handle. That continues until the exception is handled. This happens with or without try/catch around a function call. In other words, if a function is called that isn't in a try block, an exception that happens in that function will automatically be passed up to call stack. So, all you need to do is put the top-most function in a try block and handle the exception "..." in the catch block. That exception will catch all exceptions. So, your top-most function will look something like

    int main()
    {
      try
      {
        top_most_func()
      }
      catch(...)
      {
        // handle all exceptions here
      }
    }
    

    If you want to have specific code blocks for certain exceptions, you can do that too. Just make sure those occur before the "..." exception catch block.

提交回复
热议问题