無限循環是由於每次恢復執行時重新拋出異常而導致的。無需在過濾器中設置值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/s)中的s被視爲一個常量零,因爲在正常的C/C++控制流程中沒有任何其他值。 – arx 2014-11-14 18:01:03
你使用什麼編譯器?我使用C++ Builder,並且你所顯示的對我來說工作正常,我可以按預期的方式看到'code1','code2'和'code4'。 – 2014-11-14 18:04:46
@RemyLebeau來自Visual Studio 2008的VC編譯器 – user1761982 2014-11-14 18:22:40