C++ C++;-在不丢失调用堆栈的情况下处理异常
有一种方法可以处理异常,然后转到下一行 在引发异常的代码中 例如:C++ C++;-在不丢失调用堆栈的情况下处理异常,c++,exception,C++,Exception,有一种方法可以处理异常,然后转到下一行 在引发异常的代码中 例如: 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 &l
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
}
我认为一种解决方案是编写一个函数来处理每个输入的异常,并在每个语句中使用相同的异常
cout << "Test Begin! 1... 2... 3..." << endl;
handleException(A text!);
handleException(1);
handleException(2);
handleException(3);
cout << "Yeah! Successful!!" << endl;
这不是异常的工作方式。异常有效地从抛出它的函数中“返回”(更像是“退出”),清除本地分配的任何内存。这是
try
块中的一个独特事件,无法绕过
我想说的是,你的设计可能不适合C++异常,你应该重新思考如何在C++中解决问题,而不是让语言按照你想解决的方式工作。最终的结果肯定是更干净的代码
如果用try/catch
环绕函数调用,则调用堆栈可以保留,然后只展开一个函数调用,其余调用堆栈保持不变。和#定义:
不可以。您要求的是可恢复的异常,其中catch子句可以告诉程序在抛出时恢复,可能是因为catch子句中的代码修复了问题。C++不支持可恢复异常。从来没有,将来也不会<代码>但是如果我不想回滚调用堆栈?无法确定异常之前调用堆栈是什么?您所说的
是什么意思?我不想回滚调用堆栈?不确定。我认为您希望执行语句2,即使语句1抛出异常。上面的代码示例就是这样做的。当然,可以添加更多的try/catch块。在采用这种方法之前,请先看一看。您是否在我的脑海中阅读过;)我刚刚准备了相同的解决方案(),但做第二名并不有趣。我讨厌“做不到”的答案——所以+1。
cout << "Test Begin! 1... 2... 3..." << endl;
handleException(A text!);
handleException(1);
handleException(2);
handleException(3);
cout << "Yeah! Successful!!" << endl;
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;
}
}
#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!!