您的位置:首页 > 其它

C ++ 函数后面加throw()的作用

2015-09-09 09:07 330 查看
Following declaration gives a message to the user of your class: my method

doesn't throw any exception. Don't bother to put a try/catch block around it

when you use it.

void A::foo() throw();

It's your responsibility not to throw an exception in the definition of your

method.

Say

void A::foo() throw() {

throw (5); // you are doomed here.

}

The compiler won't give an error on above code. But you will get a run time

error (your program aborts) if you implemented it this way.

/////////////////////////////////

成员函数声明后面跟上throw(),表示告诉类的使用者:我的这个方法不会抛出异常,所以,在使用该方法的时候,不必把它至于 try/catch 异常处理块中。

声明一个不抛出异常的函数后,你有责任保证在你的函数的实现里面不会抛出异常。

void A::foo() throw() {

throw (5); // 程序会在这里崩溃.(编者注:如果该异常被处理,不会崩溃)

}

编译器不会认为上面的代码存在错误,(编者注:vc2005会给出警告:warning C4297: “foo”: 假定函数不引发异常,但确实发生了)但是,如果该异常未被上层的异常过滤器捕捉的话,会引发运行时的错误。

/////////////////////////////////

综上述:

1) 函数后面声明 throw() 只是接口的提供者和接口的使用者间的默契或称协议。

2) 这种协议不影响正常的异常处理流程。

3) vc2005 会在编译器对这种协议的遵守情况进行检查,并在为遵守协议的情况下 给出警告。

同理, 函数后面可以跟上 throw( int ),表示该函数可能会抛出 int型的异常。但不会抛出别的类型的异常。使用者应该注意捕获 该函数可能抛出的int型的异常

文章转自:http://blog.csdn.net/zdl1016/article/details/4204025
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: