C - 处理异常而不会丢失呼叫箱
C++ - Handling exceptions without losing the callstack
有一种处理异常的方法,然后移至下一行在抛出例外的代码中?
示例:
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>
相关文章:
- 警告处理为错误这里有什么问题
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 使用流处理接收到的数据
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 基于多个条件处理地图中的所有元素
- 如何用数字处理log(0)
- 呼叫运营商<<临时
- SSL上的`curl_easy_send`和`curl_asy_recv`:如何处理`CURLE_AGAIN`
- 错误处理.将系统错误代码映射到泛型
- 从文本文件中读取时钟时间和事件时间并进行处理
- 在运行时处理类型擦除的数据-如何不重新发明轮子
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 用于矢量处理的多个线程
- 对字符串进行排序时,在c++中处理sort()
- 在运行时呼叫处理constexPR.C
- C - 处理异常而不会丢失呼叫箱
- 如何处理塞班C++中的绿键(呼叫按钮)事件