The document discusses exception handling in C++. It defines synchronous and asynchronous exceptions and explains the purpose of exceptions is to detect and report exceptional circumstances so appropriate action can be taken. It describes the exception handling mechanism using try, throw, and catch keywords. It explains that exceptions can be rethrown from a catch block to propagate the exception outward. It provides examples of rethrowing an exception and creating a user-defined exception by inheriting from the standard exception class.
2. Exception
Exception are of two types:
Synchronous exceptions- Errors such as “out-
of-range index” and “overflow”.
Asynchronous exceptions- Errors that are
caused by the events beyond the control of the
program.
Purpose- to provide means to detect and
report an “exceptional circumstance” so that
appropriate action can be taken.
3. Error handling code
The error handling code performs the following
tasks:
1. Find the problem (Hit the exception),
2. Inform that an error has occurred (Throw the
exception),
3. Receive the error info (Catch the exception)
and
4. Take corrective action (Handle the
exception).
4. Exception handling mechanism
Try: The keyword try is used to preface a block
of statements which may generate exceptions.
Throw: Exception is thrown using throw
statement in try block.
Catch: Catches the exception thrown by the
throw statement in the try block.
5. Rethrowing an Exception
Rethrowing an expression from within an
exception handler can be done by calling
throw, by itself, with no exception (without
arguments).
This causes the current exception to be
passed on to an outer try/catch sequence.
An exception can only be rethrown from within
a catch block.
When an exception is rethrown, it is
propagated outward to the next catch block.
7. User Defined Exception
#include <iostream>
#include <exception>
using namespace std;
struct MyException : public
exception
{
const char * what () const
throw ()
{
return "C++ Exception";
}
};
int main()
{
try
{ throw MyException(); }
catch(MyException& e)
{
std::cout << "MyException
caught" << std::endl; std::cout
<< e.what() << std::endl;
}
}
8. User Defined Exception
The example shows the use of std::exception
class to implement user defined exception.
what() -- is a public method provided by
exception class and it has been overridden by
all the child exception classes. This returns the
cause of an exception.