c++ - 在递归 C++ 函数中捕获 "Stack Overflow"异常

标签 c++ exception exception-handling recursion

是否可以在递归 C++ 函数中捕获 堆栈溢出异常?如果是,怎么办?

那么在这种情况下会发生什么

void doWork()
{

     try() {

     doWork();    
     }


     catch( ... )  {

     doWork();    
     }
}  

我不是在寻找特定操作系统的答案。一般情况下

最佳答案

这本身并不是一个异常(exception),但如果您只是想将堆栈使用量限制在固定数量,您可以这样做:

#include <stdio.h>

// These will be set at the top of main()
static char * _topOfStack;
static int _maxAllowedStackUsage;

int GetCurrentStackSize()
{
   char localVar;
   int curStackSize = (&localVar)-_topOfStack;
   if (curStackSize < 0) curStackSize = -curStackSize;  // in case the stack is growing down
   return curStackSize;
}

void MyRecursiveFunction()
{
   int curStackSize = GetCurrentStackSize();
   printf("MyRecursiveFunction:  curStackSize=%i\n", curStackSize);

   if (curStackSize < _maxAllowedStackUsage) MyRecursiveFunction();
   else
   {
      printf("    Can't recurse any more, the stack is too big!\n");
   }
}

int main(int, char **)
{
   char topOfStack;
   _topOfStack = &topOfStack;
   _maxAllowedStackUsage = 4096;  // or whatever amount you feel comfortable allowing

   MyRecursiveFunction();
   return 0;
}

关于c++ - 在递归 C++ 函数中捕获 "Stack Overflow"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1578878/

相关文章:

c++ - 从 std::array 等获取 size_type 的惯用方法

c++ - C++ 中的度量单位

android - 设置 Thread.setDefaultUncaughtExceptionHandler 会阻止 Google 的错误报告工作吗?

c++ - Eclipse创建项目每次运行单个文件?

c++ - 在以下上下文中,指针和数组之间有什么区别?

c# - 创建新的 WPF 项目时已添加具有相同键的项目

java - 预订应用程序中的 NullPointerException

java - 如何编写不需要try/catch的异常?

c# - SQL 服务器 : Rethrow exception with the original exception number

java - 批量更新异常 : the batch will not terminate