Exceptions in the C ++ Specification

Source: Internet
Author: User
Document directory
  • Exception specifications
  • Standard exceptions

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

To catch exceptions we must place a portion of code under exception inspection. This is done by enclosing that portion of code inTry 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 keywordCatch, 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 inTryBlock. In this example this Code simply throws an exception:

throw 20;

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

The exception handler is declared withCatchKeyword. As you can see, it follows immediately the closing brace ofTryBlock. 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 parameterCatch, That handler will catch any exception no matter what the type ofThrowException 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 wocould catch any exception thrown with any parameter that is neitherIntNor
Char.

After an exception has been handled the program execution resumes afterTry-catchBlock, not afterThrowStatement !.

It is also possible to nestTry-catchBlocks within more externalTryBlocks. In these cases, we have the possibility that an internalCatchBlock forwards the exception to its external level. This is done with the expressionThrow;
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 appendingThrowSuffix to the function declaration:

float myfunction (char param) throw (int);

This declares a function calledMyfunctionWhich takes one argument of TypeCharAnd returns an element of Type
Float. The only exception that this function might throw is an exception of TypeInt. If it throws an exception with a different type, either directly or indirectly, it cannot be caught by a regularInt-Type handler.

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

1
2
int myfunction (int param) throw(); // no exceptions allowedint 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 calledExceptionAnd is defined in
<Exception>Header file underNamespace std. This class has the usual default and copy constructors, operators and Destructors, plus an additional virtual member function calledWhatThat 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 ourMyexObject of classMyexception.

All exceptions thrown by components of the c ++ standard library throw exceptions derived from thisSTD: exceptionClass. 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 operatorNewAnd the memory cannot be allocated, an exception of TypeBad_allocIs 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 forceBad_allocException to see it in action, you can try to allocate a huge array; on my system, trying to allocate 1 billionIntS threw
Bad_allocException.

BecauseBad_allocIs derived from the standard base classException, We can handle that same exception by catching references toExceptionClass:

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;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.