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 |
// exceptions#include <iostream>using int
|
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 |
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 |
try
catch catch catch |
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 |
try
catch
|
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 |
This declares a function called myfunction which takes one agument 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 |
int int |
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 |
// standard exceptions#include <iostream>#include <exception>using class
int
|
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 |
try
catch
|
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 |
// bad_alloc standard exception#include <iostream>#include <exception>using int
|
Type Casting
Converting an expression of a given type
into another type is known as type-casting. We have already seen some
ways to type cast:
Implicit conversions do not require any
operator. They are automatically performed when a value is copied to a
compatible type. For example:
|
1 |
shortint
|
Here, the value of a has been promoted from short to int
and we have not had to specify any type-casting operator. This is known as a
standard conversion. Standard conversions affect fundamental data types, and
allow conversions such as the conversions between numerical types (short to int,
int to float, double to
int...), to or from bool, and some pointer conversions. Some of
these conversions may imply a loss of precision, which the compiler can signal
with a warning. This can be avoided with an explicit conversion.
Implicit conversions also include
constructor or operator conversions, which affect classes that include specific
constructors or operator functions to perform conversions. For example:
|
1 |
classclass
|
Here, a implicit conversion happened
between objects of class A and class B, because B
has a constructor that takes an object of class A
as parameter. Therefore implicit conversions from A
to B are allowed.
C++ is a strong-typed language. Many
conversions, specially those that imply a different interpretation of the
value, require an explicit conversion. We have already seen two notations for
explicit type conversion: functional and c-like casting:
|
1 |
shortint
|
The functionality of these explicit
conversion operators is enough for most needs with fundamental data types.
However, these operators can be applied indiscriminately on classes and
pointers to classes, which can lead to code that while being syntactically
correct can cause runtime errors. For example, the following code is
syntactically correct:
|
1 |
// class type-casting#include <iostream>using class
class
int
|
The program declares a pointer to CAddition, but then it assigns to it a reference
to an object of another incompatible type using explicit type-casting:
|
|
|
Traditional explicit type-casting allows
to convert any pointer into any other pointer type, independently of the types
they point to. The subsequent call to member result
will produce either a run-time error or a unexpected result.
In order to control these types of
conversions between classes, we have four specific casting operators: dynamic_cast, reinterpret_cast,
static_cast and const_cast. Their format is to follow the new
type enclosed between angle-brackets (<>)
and immediately after, the expression to be converted between parentheses.
dynamic_cast
<new_type> (expression)
reinterpret_cast
<new_type> (expression)
static_cast
<new_type> (expression)
const_cast
<new_type> (expression)
The traditional type-casting equivalents to these
expressions would be:
(new_type) expression
new_type (expression)
but each one with its own special characteristics:
dynamic_cast can be used only with pointers and references to
objects. Its purpose is to ensure that the result of the type conversion is a
valid complete object of the requested class.
Therefore, dynamic_cast
is always successful when we cast a class to one of its base classes:
|
1 |
classclass
|
The second conversion in this piece of
code would produce a compilation error since base-to-derived conversions are
not allowed with dynamic_cast unless the
base class is polymorphic.
When a class is polymorphic, dynamic_cast performs a special checking during
runtime to ensure that the expression yields a valid complete object of the
requested class:
|
1 |
// dynamic_cast#include <iostream>#include <exception>using class class int
|
Null pointer on second type-cast |
|
Compatibility note: dynamic_cast requires the
Run-Time Type Information (RTTI) to keep track of dynamic types. Some
compilers support this feature as an option which is disabled by default.
This must be enabled for runtime type checking using dynamic_cast to work properly. |
The code tries to perform two dynamic
casts from pointer objects of type CBase* (pba and pbb)
to a pointer object of type CDerived*,
but only the first one is successful. Notice their respective initializations:
|
1 |
|
Even though both are pointers of type CBase*, pba
points to an object of type CDerived,
while pbb points to an object of
type CBase. Thus, when their
respective type-castings are performed using dynamic_cast,
pba is pointing to a full
object of class CDerived, whereas pbb is pointing to an object of class CBase, which is an incomplete object of class CDerived.
When dynamic_cast
cannot cast a pointer because it is not a complete object of the required class
-as in the second conversion in the previous example- it returns a null pointer
to indicate the failure. If dynamic_cast
is used to convert to a reference type and the conversion is not possible, an
exception of type bad_cast is thrown instead.
dynamic_cast can also cast null pointers even between pointers to
unrelated classes, and can also cast pointers of any type to void pointers (void*).
static_cast can perform conversions between pointers to related
classes, not only from the derived class to its base, but also from a base
class to its derived. This ensures that at least the classes are compatible if
the proper object is converted, but no safety check is performed during runtime
to check if the object being converted is in fact a full object of the
destination type. Therefore, it is up to the programmer to ensure that the
conversion is safe. On the other side, the overhead of the type-safety checks
of dynamic_cast is avoided.
|
1 |
classclass
|
This would be valid, although b would point to an incomplete object of the
class and could lead to runtime errors if dereferenced.
static_cast can also be used to perform any other non-pointer
conversion that could also be performed implicitly, like for example standard
conversion between fundamental types:
|
1 |
doubleint |
Or any conversion between classes with
explicit constructors or operator functions as described in "implicit
conversions" above.
reinterpret_cast converts any pointer type to any other pointer type,
even of unrelated classes. The operation result is a simple binary copy of the
value from one pointer to the other. All pointer conversions are allowed:
neither the content pointed nor the pointer type itself is checked.
It can also cast pointers to or from
integer types. The format in which this integer value represents a pointer is
platform-specific. The only guarantee is that a pointer cast to an integer type
large enough to fully contain it, is granted to be able to be cast back to a
valid pointer.
The conversions that can be performed by reinterpret_cast but not by static_cast have no specific uses in C++ are
low-level operations, whose interpretation results in code which is generally
system-specific, and thus non-portable. For example:
|
1 |
classclass
|
This is valid C++ code, although it does
not make much sense, since now we have a pointer that points to an object of an
incompatible class, and thus dereferencing it is unsafe.
This type of casting manipulates the
constness of an object, either to be set or to be removed. For example, in
order to pass a const argument to a function that expects a non-constant
parameter:
|
1 |
// const_cast#include <iostream>using void int
|
sample text |
typeid allows to check the type of an expression:
typeid
(expression)
This operator returns a reference to a
constant object of type type_info that is defined
in the standard header file <typeinfo>.
This returned value can be compared with another one using operators == and != or can
serve to obtain a null-terminated character sequence representing the data type
or class name by using its name()
member.
|
1 |
// typeid#include <iostream>#include <typeinfo>using int
|
a and b are of different types:a is: int *b is: int |
When typeid
is applied to classes typeid uses the RTTI to
keep track of the type of dynamic objects. When typeid is applied to an
expression whose type is a polymorphic class, the result is the type of the
most derived complete object:
|
1 |
// typeid, polymorphic class#include <iostream>#include <typeinfo>#include <exception>using class class int
|
a is: class CBase *b is: class CBase **a is: class CBase*b is: class CDerived |
Notice how the type that typeid considers for pointers is the pointer
type itself (both a and b are of type class
CBase *). However, when typeid is
applied to objects (like *a and *b) typeid
yields their dynamic type (i.e. the type of their most derived complete
object).
If the type typeid
evaluates is a pointer preceded by the dereference operator (*), and this pointer has a null value, typeid throws a bad_typeid
exception.