今天看Thinking in C++ 2nd v2第一章的关于set_unexpected, 测试书里的代码, 发现和书上的结果不同, 代码如下:

//: C01:BadException.cpp {-bor}
#include <exception>    // For std::bad_exception
#include <iostream>
#include <cstdio>
using namespace std;
// Exception classes:
class A {};
class B {};
// terminate() handler
void my_thandler() {
  cout << "terminate called" << endl;
  exit(0);
}
// unexpected() handlers
void my_uhandler1() { throw A(); }
void my_uhandler2() { throw; }
// If we embed this throw statement in f or g,
// the compiler detects the violation and reports
// an error, so we put it in its own function.
void t() { throw B(); }
void f() throw(A) { t(); }
void g() throw(A, bad_exception) { t(); }
int main() {
  set_terminate(my_thandler);
  set_unexpected(my_uhandler1);
try {
    f();
  } catch(A&) {
    cout << "caught an A from f" << endl;
  }
  set_unexpected(my_uhandler2);
try {
    g();
  } catch(bad_exception&) {
    cout << "caught a bad_exception from g" << endl;
  }
try {
    f();
  } catch(...) {
    cout << "This will never print" << endl;
  }
} ///:~

 

书上说结果将会调用自定义的异常handler:

caught an A from f

caught a bad_exception from g

terminate called

可我用Visual C++运行的结果是:

terminate called

立刻跑到Google搜索, 结果搜到MSDN关于set_unexpected的页面:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccore98/html/_crt_set_unexpected.asp

MSDN最后说:

In the current Microsoft implementation of C++ exception handling, unexpected calls terminate by default and is never called by the exception-handling run-time library. There is no particular advantage to calling unexpected rather than terminate.

噢, 微软就是牛哈, 说不支持就是不支持~ 不过感觉微软做的也对, 这些东东用多了代码就会变的很乱了.  像这种问题还是应该使用良好的设计来避免~

Posted on 2006-10-18 20:29  Adrian H.  阅读(1242)  评论(0编辑  收藏  举报