我写了代码
void SEHtest(int i) {
int s = 0;
__try {
cout << "code1" << endl;
int j = 1 / s;
cout << "code2" << endl;
} __except((s = 1, i)) {
cout << "code3" << endl;
}
cout << "code4" << endl;
return;
}
int main() {
SEHtest(-1);
return 0;
}
我正在等待输出
code1
code2
code4
但我只有
code1
和无限循环。
为什么?
将
volatile
密钥名添加到s和j不能解决问题。 最佳答案
导致无限循环是因为每次您恢复执行时都会重新引发异常。不必在过滤器中设置s = 1
的值,因为执行是从引起陷阱的指令(在这种情况下为零除)中恢复执行的。如果按照以下方式重新组织代码,您将看到不断抛出异常:
int ExceptionFilter(int& s) {
cout << "exception filter with s = " << s << endl;
s++;
return -1; // EXCEPTION_CONTINUE_EXECUTION
}
void SEHtest() {
int s = 0;
__try {
cout << "before exception" << endl;
int j = 1 / s;
cout << "after exception" << endl;
} __except(ExceptionFilter(s)) {
cout << "exception handler" << endl;
}
cout << "after try-catch" << endl;
return;
}
int main() {
SEHtest();
return 0;
}
结果应为:
before exception
exception filter with s = 0
exception filter with s = 1
exception filter with s = 2
...
继续抛出异常是因为执行是在被零除的指令上执行,而不是在加载s值的指令上执行。这些步骤是:
1 set a register to 0
2 store that register in s (might be optimized out)
3 enter try block
4 output "before exception"
5 load a register from s
6 divide 1 by register (trigger exception)
7 jump to exception filter
8 in filter increment/change s
9 filter returns -1
10 execution continues on line 6 above
6 divide 1 by register (trigger exception)
7 jump to exception filter
8 in filter increment/change s
9 filter returns -1
10 execution continues on line 6 above
...
我认为您无法从该例外中恢复。
关于c++ - EXCEPTION_CONTINUE_EXECUTION奇怪的行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26935823/