0

我写了代码

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 并没有解决它。

4

2 回答 2

4

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

我认为您无法从该异常中恢复。

于 2014-11-14T18:15:27.487 回答
0

如果您希望执行最后一部分,请尝试将整个内容包含在另一个中

__try { 
 < your code>
}
__finally{
    < code that will be executed at end>
}

有关更多信息,请查看此处此处

不会显示带有“代码 2”的行,因为执行被上一行的异常中断。

于 2014-11-14T17:50:54.117 回答