beautypg.com

Using exceptions – HP Integrity NonStop H-Series User Manual

Page 224

background image

Click on the banner to return to the user guide home page.

©Copyright 1996 Rogue Wave Software

Using Exceptions

All exceptions thrown explicitly by any element of the library are guaranteed to be part of the
standard exception hierarchy. Review the reference for these classes to determine which
functions throw which exceptions. You can then choose to catch particular exceptions, or catch
any that might be thrown (by specifying the base class exception).

For instance, if you are going to call the insert function on

string

with a position value that

could at some point be invalid, then you should use code like this:

string s;
int n;
...
try
{
s.insert(n,"Howdy");
}
catch (const exception& e)
{
// deal with the exception
}

To throw your own exceptions, simply construct an exception of an appropriate type, assign it
an appropriate message and throw it. For example:

...
if (n > max)
throw out_of_range("Your past the end, bud");

The class

exception

serves as the base class for all other exception classes. As such it defines a

standard interface. This interface includes the what() member function, which returns a
null-terminated string that represents the message that was thrown with the exception. This
function is likely to be most useful in a catch clause, as demonstrated in the example program at
the end of this section.

The class

exception

does not contain a constructor that takes a message string, although it can

be thrown without a message. Calling what() on an exception object will return a default
message. All classes derived from exception do provide a constructor that allows you to specify
a particular message.

This manual is related to the following products: