您的位置:首页 > 编程语言 > C语言/C++

C++ 异常处理

2010-09-03 19:56 295 查看
http://msdn.microsoft.com/en-us/library/6dekhbbc(VS.80).aspx 摘来的,很容易理解C++的异常处理机制。注意如果异常被捕获,那么后续的代码可以继续执行,反之则后续代码均不会被执行(参考最后的那个例子)

The following syntax shows a try block and its handlers:

Copy

try {
// code that could throw an exception
}
[ catch (exception-declaration) {
// code that executes when exception-declaration is thrown
// in the try block
}
[catch (exception-declaration) {
// code that handles another exception type
} ] . . . ]
// The following syntax shows a throw expression:
throw [expression]


Remarks

The C++ language provides built-in support for handling anomalous situations, known as exceptions, which may occur during the execution of your program. The try, throw, and catch statements implement exception handling. With C++ exception handling, your program can communicate unexpected events to a higher execution context that is better able to recover from such abnormal events. These exceptions are handled by code which is outside the normal flow of control. The Microsoft C++ compiler implements the C++ exception handling model based on the ANSI C++ standard.

C++ also provides a way to explicitly specify whether or a function could throw exceptions. Exception specifications are used in function declarations to indicate that a function could throw an exception. For example, an exception specification throw(...) tells the compiler that a function could throw an exception, but doesn't specify the type. For example:

Copy

void MyFunc()  throw(...) {
throw 1;
}


For more information, see Exception Specifications.


Note
The Win32 structured exception-handling mechanism works with both C and C++ source files. However, it is not specifically designed for C++. You can ensure that your code is more portable by using C++ exception handling. Also, C++ exception handling is more flexible, in that it can handle exceptions of any type. For C++ programs, it is recommended that you use the C++ exception-handling mechanism (try, catch,throw) described in this topic.

The code after the try clause is the guarded section of code. The throw expression throws (raises) an exception. The code block after the catchclause is the exception handler, and catches (handles) the exception thrown by the throw expression. The exception-declaration statement indicates the type of exception the clause handles. The type can be any valid data type, including a C++ class. If the exception-declarationstatement is an ellipsis (...), the catch clause handles any type of exception, including C exceptions and system- or application-generated exceptions such as memory protection, divide by zero, and floating-point violations. Such a handler must be the last handler for its try block.

The operand of throw is syntactically similar to the operand of a return statement.

Execution proceeds as follows:

Control reaches the try statement by normal sequential execution. The guarded section within the try block is executed.

If no exception is thrown during execution of the guarded section, the catch clauses that follow the try block are not executed. Execution continues at the statement after the last catch clause following the try block in which the exception was thrown.

If an exception is thrown during execution of the guarded section or in any routine the guarded section calls (either directly or indirectly), an exception object is created from the object created by the throw operand. (This implies that a copy constructor may be involved.) At this point, the compiler looks for a catch clause in a higher execution context that can handle an exception of the type thrown (or a catchhandler that can handle any type of exception). The catch handlers are examined in order of their appearance following the try block. If no appropriate handler is found, the next dynamically enclosing try block is examined. This process continues until the outermost enclosing tryblock is examined.

If a matching handler is still not found, or if an exception occurs while unwinding, but before the handler gets control, the predefined run-time function terminate is called. If an exception occurs after throwing the exception, but before the unwind begins, terminate is called.

If a matching catch handler is found, and it catches by value, its formal parameter is initialized by copying the exception object. If it catches by reference, the parameter is initialized to refer to the exception object. After the formal parameter is initialized, the process of unwinding the stack begins. This involves the destruction of all automatic objects that were constructed (but not yet destructed) between the beginning of the try block associated with the catch handler and the exception's throw site. Destruction occurs in reverse order of construction. The catch handler is executed and the program resumes execution following the last handler (that is, the first statement or construct which is not a catch handler). Control can only enter a catch handler through a thrown exception, never via a goto statement or a case label in a switch statement.

The following is a simple example of a try block and its associated catch handler. This example detects failure of a memory allocation operation using the new operator. If new is successful, the catch handler is never executed:

Copy

// exceptions_trycatchandthrowstatements.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
int main() {
char *buf;
try {
buf = new char[512];
if( buf == 0 )
throw "Memory allocation failure!";
}
catch( char * str ) {
cout << "Exception raised: " << str << '/n';
}
}


The operand of the throw expression specifies that an exception of type char * is being thrown. It is handled by a catch handler that expresses the ability to catch an exception of type char *. In the event of a memory allocation failure, this is the output from the preceding example:

Copy

Exception raised: Memory allocation failure!


The real power of C++ exception handling lies not only in its ability to deal with exceptions of varying types, but also in its ability to automatically call destructor functions during stack unwinding, for all local objects constructed before the exception was thrown.

The following example demonstrates C++ exception handling using classes with destructor semantics:

Example

Copy

// exceptions_trycatchandthrowstatements2.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
void MyFunc( void );

class CTest {
public:
CTest() {};
~CTest() {};
const char *ShowReason() const {
return "Exception in CTest class.";
}
};

class CDtorDemo {
public:
CDtorDemo();
~CDtorDemo();
};

CDtorDemo::CDtorDemo() {
cout << "Constructing CDtorDemo./n";
}

CDtorDemo::~CDtorDemo() {
cout << "Destructing CDtorDemo./n";
}

void MyFunc() {
CDtorDemo D;
cout<< "In MyFunc(). Throwing CTest exception./n";
throw CTest();
}

int main() {
cout << "In main./n";
try {
cout << "In try block, calling MyFunc()./n";
MyFunc();
}
catch( CTest E ) {
cout << "In catch handler./n";
cout << "Caught CTest exception type: ";
cout << E.ShowReason() << "/n";
}
catch( char *str )    {
cout << "Caught some other exception: " << str << "/n";
}
cout << "Back in main. Execution resumes here./n";
}


Output

In main.
In try block, calling MyFunc().
Constructing CDtorDemo.
In MyFunc(). Throwing CTest exception.
Destructing CDtorDemo.
In catch handler.
Caught CTest exception type: Exception in CTest class.
Back in main. Execution resumes here.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: