-1

有一种方法可以处理异常,然后转到引发异常的代码中的下一行?

例子:

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!!
4

4 回答 4

2

这不是异常的工作方式。异常从抛出它的函数中有效地“返回”(更像是“退出”),清除本地分配的任何内存。这是一个try街区中的独特事件,没有办法。

我想说的是,您的设计可能不适合 C++ 异常,您应该重新考虑如何在 C++ 中解决问题,而不是让语言以您想要解决问题的方式工作。最终的结果肯定会是更干净的代码。

如果用/包围一个throwing 函数的调用,则可以保留调用堆栈,这样只会展开该一个函数调用,而调用堆栈的其余部分保持不变。trycatch

于 2012-10-20T20:24:23.470 回答
1

不。您所要求的称为可恢复异常,其中 catch 子句可以告诉程序在抛出点恢复,大概是因为 catch 子句中的代码解决了问题。C++ 不支持可恢复的异常。从来没有,永远不会。<g>

于 2012-10-20T21:40:07.553 回答
1

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!!
于 2012-10-20T20:31:02.973 回答
1

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

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

handleException是/是您的异常处理的自定义函数如下(仅示例)

   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;
         }
     }
于 2012-10-20T20:18:34.330 回答