我写了代码
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
和无限循环。
为什么?
向s添加volatile
个键名,而j没有修复它。
答案 0 :(得分:3)
导致无限循环,因为每次重新执行时都会重新抛出异常。在过滤器中设置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
...
我认为你不能从那个例外中恢复。
答案 1 :(得分:0)