`
universsky
  • 浏览: 92398 次
文章分类
社区版块
存档分类
最新评论

C++ : EXCEPTIONS

 
阅读更多

Exceptions

Exceptions provide a way to react to exceptional circumstances (like runtime errors) in our program by transferring control to special functions called handlers.

To catch exceptions we must place a portion of code under exception inspection. This is done by enclosing that portion of code in a try block. When an exceptional circumstance arises within that block, an exception is thrown that transfers the control to the exception handler. If no exception is thrown, the code continues normally and all handlers are ignored.

An exception is thrown by using the throw keyword from inside the try block. Exception handlers are declared with the keyword catch, which must be placed immediately after the try block:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// exceptions
#include <iostream>
using namespace std;

int main () {
  try
  {
    throw 20;
  }
  catch (int e)
  {
    cout << "An exception occurred. Exception Nr. " << e << endl;
  }
  return 0;
}
An exception occurred. Exception Nr. 20


The code under exception handling is enclosed in a try block. In this example this code simply throws an exception:

throw 20;


A throw expression accepts one parameter (in this case the integer value 20), which is passed as an argument to the exception handler.

The exception handler is declared with the catch keyword. As you can see, it follows immediately the closing brace of the try block. The catch format is similar to a regular function that always has at least one parameter. The type of this parameter is very important, since the type of the argument passed by the throw expression is checked against it, and only in the case they match, the exception is caught.

We can chain multiple handlers (catch expressions), each one with a different parameter type. Only the handler that matches its type with the argument specified in the throw statement is executed.

If we use an ellipsis (...) as the parameter of catch, that handler will catch any exception no matter what the type of the throw exception is. This can be used as a default handler that catches all exceptions not caught by other handlers if it is specified at last:

1
2
3
4
5
6
try {
  // code here
}
catch (int param) { cout << "int exception"; }
catch (char param) { cout << "char exception"; }
catch (...) { cout << "default exception"; }


In this case the last handler would catch any exception thrown with any parameter that is neither an int nor a char.

After an exception has been handled the program execution resumes after the try-catch block, not after the throw statement!.

It is also possible to nest try-catch blocks within more external try blocks. In these cases, we have the possibility that an internal catch block forwards the exception to its external level. This is done with the expression throw; with no arguments. For example:

1
2
3
4
5
6
7
8
9
10
11
try {
  try {
      // code here
  }
  catch (int n) {
      throw;
  }
}
catch (...) {
  cout << "Exception occurred";
}


Exception specifications


When declaring a function we can limit the exception type it might directly or indirectly throw by appending a throw suffix to the function declaration:

float myfunction (char param) throw (int);


This declares a function called myfunction which takes one argument of type char and returns an element of type float. The only exception that this function might throw is an exception of type int. If it throws an exception with a different type, either directly or indirectly, it cannot be caught by a regular int-type handler.

If this throw specifier is left empty with no type, this means the function is not allowed to throw exceptions. Functions with no throw specifier (regular functions) are allowed to throw exceptions with any type:

1
2
int myfunction (int param) throw(); // no exceptions allowed
int myfunction (int param);         // all exceptions allowed 


Standard exceptions

The C++ Standard library provides a base class specifically designed to declare objects to be thrown as exceptions. It is called exception and is defined in the <exception> header file under the namespace std. This class has the usual default and copy constructors, operators and destructors, plus an additional virtual member function called what that returns a null-terminated character sequence (char *) and that can be overwritten in derived classes to contain some sort of description of the exception.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// standard exceptions
#include <iostream>
#include <exception>
using namespace std;

class myexception: public exception
{
  virtual const char* what() const throw()
  {
    return "My exception happened";
  }
} myex;

int main () {
  try
  {
    throw myex;
  }
  catch (exception& e)
  {
    cout << e.what() << endl;
  }
  return 0;
}
My exception happened.


We have placed a handler that catches exception objects by reference (notice the ampersand & after the type), therefore this catches also classes derived from exception, like our myex object of class myexception.

All exceptions thrown by components of the C++ Standard library throw exceptions derived from this std::exception class. These are:

exception description
bad_alloc thrown by new on allocation failure
bad_cast thrown by dynamic_cast when fails with a referenced type
bad_exception thrown when an exception type doesn't match any catch
bad_typeid thrown by typeid
ios_base::failure thrown by functions in the iostream library

For example, if we use the operator new and the memory cannot be allocated, an exception of type bad_alloc is thrown:

1
2
3
4
5
6
7
8
try
{
  int * myarray= new int[1000];
}
catch (bad_alloc&)
{
  cout << "Error allocating memory." << endl;
}


It is recommended to include all dynamic memory allocations within a try block that catches this type of exception to perform a clean action instead of an abnormal program termination, which is what happens when this type of exception is thrown and not caught. If you want to force a bad_alloc exception to see it in action, you can try to allocate a huge array; On my system, trying to allocate 1 billion ints threw a bad_alloc exception.

Because bad_alloc is derived from the standard base class exception, we can handle that same exception by catching references to the exception class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// bad_alloc standard exception
#include <iostream>
#include <exception>
using namespace std;

int main () {
  try
  {
    int* myarray= new int[1000];
  }
  catch (exception& e)
  {
    cout << "Standard exception: " << e.what() << endl;
  }
  return 0;
}
分享到:
评论

相关推荐

    Applied C++: practical techniquest for Building Better Software

    A C++ templates primer  Workable coding guidelines and extensive coding examples  Quick lists of need-to-know information about Exceptions, Assertions, and Standard Template Library components ...

    source insight 4.0.0089

    Fix: C++: lambda functions: misc fixes: capture variables by reference, trailing return types, specifiers and exceptions. Fix: C++: fix to pointer dereference using std::unique_ptr. Fix: Search ...

    SourceInsight4.0.0089

    4. C++: lambda functions: misc fixes: capture variables by reference, trailing return types, specifiers and exceptions. 5. C++: fix to pointer dereference using std::unique_ptr. 6. Search Results: ...

    C++ Crash Course- A Fast-Paced Introduction 2019.rar

    The object lifecycle including storage duration, memory management, exceptions, call stacks, and the RAII paradigm Compile-time polymorphism with templates and run-time polymorphism with virtual ...

    Effective C++(中文版).pdf

    为反映出现代设计考虑,对第二版论题做了广泛的修订,包括异常(exceptions)、设计模式(design patterns)和多线程(multithreading)。 《Effective C++》的重要特征包括: ·高效的 classes、functions、...

    Effective.C++中文版

    《Effective C++:改善程序与设计的55个具体做法》(中文版)(第3版)一共组织55个准则,每一条准则描述一个编写出更好的C++的方式。每一个条款的背后都有具体范例支撑。第三版有一半以上的篇幅是崭新内容,包括讨论...

    C++完全帮助文档(手册)

    C++ Exceptions * Complex Numbers C++ Standard Template Library (STL) * Overview * C++ Algorithms * C++ Vectors * C++ Double-Ended Queues * C++ Lists * C++ Priority Queues * C++ ...

    C++17 标准 ISOIEC 14882 2017 官方pdf文档

    In addition to the facilities provided by C, C++ provides additional data types, classes, templates, exceptions, namespaces, operator overloading, function name overloading, references, free store ...

    effective C++ 第三版 中文

    《Effective C++:改善程序与设计的55个具体做法》(中文版)(第3版)一共组织55个准则,每一条准则描述一个编写出更好的C++的方式。每一个条款的背后都有具体范例支撑。第三版有一半以上的篇幅是崭新内容,包括讨论...

    面向对象编程:C++与Java比较教程 英文版

    Chapter 10 - Handling Exceptions Chapter 11 - Classes, The Rest of the Story Chapter 12 - Overloading Operators in C++ Chapter 13 - Generics and Templates Chapter 14 - Modeling Diagrams for OO ...

    effective c++ 3rd英文版

    Topics from the second edition have been extensively revised to reflect modern design considerations, including exceptions, design patterns, and multithreading.Important features of Effective C++ ...

    c++ 连接 mysql 官方文档

    Contents ?MySQL C++ Driver Based on JDBC 4.0 ...Catching Exceptions ?Debug Tracing with MySQL Connector/C++ ?For More Information ?About the author ?Appendix I: Installing MySQL Connector/C++ from Source

    Practical C++ Programming C++编程实践

    Exceptions Adding Exceptions to the Stack Class Exceptions Versus assert Programming Exercises 23. Modular Programming Modules Public and Private The extern Storage Class Headers The Body of the ...

    Effective C++ 中文版

    为反映出现代设计考虑,对第二版论题做了广泛的修订,包括异常(exceptions)、设计模式(design patterns)和多线程(multithreading)。  《Effective C++中文版(第3版改善程序与设计的55个具体做法)》的重要...

    面向对象编程:C++与Java比较教程 英文精简版

    Chapter 10 - Handling Exceptions Chapter 11 - Classes, The Rest of the Story Chapter 12 - Overloading Operators in C++ Chapter 13 - Generics and Templates Chapter 14 - Modeling Diagrams for OO ...

    Effective C++中文版第三版(带完整目录)(2-1)

    为反映出现代设计考虑,对第二版论题做了广泛的修订,包括异常(exceptions)、设计模式(design patterns)和多线程(multithreading)。    《effective c++》的重要特征包括:  * 高效的 classes、functions、...

    ISO/IEC 14882 2014 Programming Languages C++

    In addition to the facilities provided by C, C++ provides additional data types, classes, templates, exceptions, namespaces, operator overloading, function name overloading, references, free store ...

    Google C++ Style Guide(Google C++编程规范)高清PDF

    Other C++ Features Reference Arguments Function Overloading Default Arguments Variable-Length Arrays and alloca() Friends Exceptions Run-Time Type Information (RTTI) Casting Streams Preincrement and ...

    More Effective C++

    和其前一本兄弟书籍 Effective C++一样,More Effective C++对每一位以C++为开发工具的程序员而言,都必备读物。  继 Effective C++ 之後,Scott Meyers 於 1996 推出这本「续集」。条款变得比较少,页数倒是多了...

    Exploring C++ 11

    Part 2: Custom Types – Exceptions Part 2: Custom Types – More Operators Part 2: Custom Types – Project2: Fixed-point Numbers Part 3: Generic Programming – Function Templates Part 3: Generic ...

Global site tag (gtag.js) - Google Analytics