C++异常处理之一

Exception specifications

Exception specifications are used to provide summary information about what exceptions can be thrown out of a function. For example:

void MyFunction(int i) throw(...);

An exception specification with an empty throw, as in

void MyFunction(int i) throw();

tells the compiler that the function does not throw any exceptions. It is the equivalent to using __declspec(nothrow).

// exceptions_trycatchandthrowstatements3.cpp
// compile with: /EHsc
#include <stdio.h>

void empty() throw() {
   puts("In empty()");
}

void with_type() throw(int) {
   puts("Will throw an int");
   throw(1);
}

int main() {
   try {
      empty();
      with_type();
   }
   catch (int) {
      puts("Caught an int");
   }
}

在VC中,throw的行为跟一下情况有关:编译的程序是C还是C++;编译器/EH选项的值;是否明确指定了 exception specification,详情请参考:http://msdn.microsoft.com/en-US/library/wfa0edys(v=vs.80)

Synchronous Exception Model

在早版本的VC中,使用的是Asynchronous Model, Under the asynchronous model, the compiler assumes any instruction may generate an exception. 

With the new synchronous exception model, now the default, exceptions can be thrown only with a throw statement. Therefore, the compiler can assume that exceptions happen only at a throw statement or at a function call. This model allows the compiler to eliminate the mechanics of tracking the lifetime of certain unwindable objects, and to significantly reduce the code size, if the objects' lifetimes do not overlap a function call or a throw statement. The two exception handling models, synchronous and asynchronous, are fully compatible and can be mixed in the same application. 

Unhandled C++ Exceptions

If a matching handler (or ellipsis catch handler) cannot be found for the current exception, the predefined terminate run-time function is called. (You can also explicitly call terminate in any of your handlers.) The default action of terminate is to call abort. If you want terminate to call some other function in your program before exiting the application, call the set_terminate function with the name of the function to be called as its single argument. You can call set_terminate at any point in your program. The terminate routine always calls the last function given as an argument to set_terminate.

Nothrow constant

This constant value is used as an argument for operator new and operator new[] to indicate that these functions shall not throw an exception on failure, but return a null pointer instead.

原文地址:https://www.cnblogs.com/whyandinside/p/2683818.html