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.
Example:
- #include <iostream>
-
using namespace std;
-
-
int
-
main(void)
-
{
-
try {
-
throw 20;
-
} catch (int e) {
-
cout << "An exception occurred." << e << endl;
-
}
-
-
return (0);
-
}
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。
- #include <iostream>
-
#include <exception>
-
using namespace std;
-
-
class myexception: public exception {
-
virtual const char *what() const throw()
-
{
-
return "My exception happened";
-
}
-
}myex;
-
-
int
-
main(void)
-
{
-
try
-
{
-
throw myex;
-
}
-
catch (exception &e)
-
{
-
cout << e.what() << endl;
-
}
-
-
return (0);
-
}
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
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.
All exceptions thrown by components of the C++ Standard library throw exceptions derived from this std::exception class.
阅读(906) | 评论(0) | 转发(0) |