EXCEPTION CONTINUE EXECUTION奇怪的行为

时间:2014-11-14 17:42:03

标签: c++ winapi seh

我写了代码

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没有修复它。

2 个答案:

答案 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)

如果你想要执行最后一部分,请尝试将整个部分包含在另一部分

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

有关详细信息,请查看herehere

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