C - 处理异常而不会丢失呼叫箱

C++ - Handling exceptions without losing the callstack

本文关键字:呼叫 处理 异常      更新时间:2023-10-16

有一种处理异常的方法,然后移至下一行在抛出例外的代码中?

示例:

try {
    cout << "Test Begin! 1... 2... 3..." << endl;
    throw "A text!";
    throw 1;
    throw 2;
    throw 3;
    cout << "Yeah! Successful!!" << endl;
} catch (char* text) {
    cout << ch << endl;
    ???(); //Go back to the previous line
}
catch (int i) {
    cout << "Thrown " << i << endl;
    ???(); //Go back to the previous line
}

输出将为:

Test Begin! 1... 2... 3...
A text!
Thrown 1
Thrown 2
Thrown 3
Yeah! Successful!!

这不是例外的工作方式。有效地从其赋予的函数中有效地"返回" S(更像"退出" S),清理本地分配的任何内存。这是try块中的独特事件,无法解决。

我要说的是,您的设计可能不适合C 例外,您应该重新考虑如何解决C 中的问题,而不是以您想要解决问题的方式使语言起作用。最终结果肯定是最后的代码。

如果您用try/catch包围throw ING函数的呼叫,则可以保留呼叫堆栈,然后只能放松一个函数调用,使呼叫堆栈的其余部分完整。

longjmp和#define:

#include <setjmp.h>
#include <iostream>
#define THROW_AND_GO_NEXT(action) 
  val=setjmp(env); 
  if (val==0) 
    action; 

using namespace std;
int main()
{
  jmp_buf env;
  int val;
  try {
      cout << "Test Begin! 1... 2... 3..." << endl;
      THROW_AND_GO_NEXT(throw "A text!");
      THROW_AND_GO_NEXT (throw 1);
      THROW_AND_GO_NEXT(throw 2);
      THROW_AND_GO_NEXT(throw 3);
      cout << "Yeah! Successful!!" << endl;
  } catch (const char* text) {
      cout << text << endl;
      longjmp(env,1);
  }
  catch (int i) {
      cout << "Thrown " << i << endl;
      longjmp(env,1);
  }
  return 0;
}

这是输出:

>./a
Test Begin! 1... 2... 3...
A text!
Thrown 1
Thrown 2
Thrown 3
Yeah! Successful!!

我认为一个解决方案可以是编写一个函数来处理每个输入的异常,并在每个语句中使用相同的函数,例如。

   cout << "Test Begin! 1... 2... 3..." << endl;
   handleException(A text!);
   handleException(1);
   handleException(2);
   handleException(3);
   cout << "Yeah! Successful!!" << endl;

此处 handleException是/是自定义函数(s),其异常处理如下(示例)

   void handleException(int input){
      try {
           thrown input;
         }catch (int i) {
            cout << "Thrown " << i << endl;
         }
     }

   void handleException(char* input){
      try {
           thrown input;
         }catch (char* text) {
            cout << "Thrown " << text << endl;
         }
     }

no。您所要求的内容称为 requmable 例外,其中捕获子句可以在投掷时告诉程序 remume ,大概是因为代码中的代码捕获子句解决了问题。C 不支持重新启动例外。从来没有做过,永远不会。<g>