导致无限循环的原因是每次恢复执行时都会重新抛出异常。在过滤器中设置 的值并不重要,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
...
我认为您无法从该异常中恢复。