An exception is a situation in which program cannot handle unexpected circumstances and results in crash.
The unexpected circumstances may arise only in one function but the whole program gets crashed. You can’t eliminate the exceptional circumstances but you can prepare for them.
C++ have a mechanism to handle the exception for that code or function only that might generate such situation.
And c++ also has a flexibility to create own class to handle user defined situations/exceptions.
How the exceptions are generated?
Let’s consider some simple example:
- If your program requests to dynamically allocate an object using new operator, and there is not any memory available.
- One of the most common math errors by dividing by zero.
In both situations program gets crashed.
What is exception handling?
The technique through which a run time error is caught by a handler so that your program remains alive.
C++ uses try, throw, catch keywords to handle an exception.
The try block contains the statement(s) which is supposed to generate an exception.
And throw statement will throw the exception to catch block.
“Catch” block catches the exception if “catch” block has the handler class to handle that exception. Otherwise exception is passed to next “catch” block if exists. If no exception class is able to handle the exception then program stops working and crashes.
try-catch
using namespace std;
int main()
{
char* ptr;
try
{
ptr = new char[~size_t(0)/2];
delete []ptr;
}
catch( bad_alloc &ba)
{
cout << ba.what( ) << endl;
}
return 0;
}
In the above example we are trying to allocate more than existing memory such that exception will produce.
bad_alloc is a drived class from exception class that is used when program is not able to allocate the desired memory.
The statement “delete []ptr;” will not execute because “new” is generating an exception and control goes to catch block. So after executing “catch” block control will transfer to next statement i.e “return 0;”
try-throw-catch
int main ()
{
try
{
throw 10;
}
catch(int a)
{
cout<<"An integer exception handler";
}
catch (const char* ch)
{
cout<<"A string exception handler";
}
catch (...)
{
cout<<"A common handler";
}
}
“throw” is used to throw an exception, generally used in user defined class to simulate an exceptional situation.
Here try block is having an exceptional statement and catch block is ready to catch the integer type exception.
So it means you need to use number of catch block to handle all types of exceptions but anyhow it is not possible.
So c++ provides you a generic catch block that can catch any type of exception i.e (...)
No comments:
Post a Comment