Saturday, 1 February 2014

EXCEPTION IN C++

 



Exception is one which is used to handle the unexpected situations.

Need for exception:
While coding small programs exception case may find not useful.  At the same time while developing the huge applications exception is a good friend to the programmers.

Consider the scenario, that you are using the database  in your program, you cannot be sure that database connectivity will always be there. At sometimes the database connectivity may go down. As a programmer we need to handle this situation. Here exception is useful.
So write a exception here, whenever the exception occurs display the alert message.
If exception is not handled properly then our program will crash and stops running.

try throw catch blocks:

try block:
Whenever you feel the exception occur place the code in try block.
try
{
// Code for which exception occurs
}

catch block:
Whenever error occurs, catch block will be called
catch(int a)
{
     
}

throw block:
Whenever you feel the exception will occur, use a throw statement. Whenever the throw statement is encountered then the catch block will be called.

Throw after the funciton signature:
The throw after the method signature is used for unhandled exceptions. If you feel that some exceptions are no need to be handled by the function you can use the throw after the method signature.
There will be no catch block will be called for that throw statement.
The exception that is mentioned in the type list only will be thrown. other exceptions will not be handled if exception occurs then the program will crash.

void myfunction(int a)throws (int a, std::logic_error)
{
---
}
In above code, only int error and logic error that was caught by program will be thrown. It means you no need to throw anystatment for int and logic error. It is automatic. when other error occurs the program will crash.

One sad news is that this one was depreciated in c++ 11.


Ellipis operator in catch block:

Triple dot  “…”  is the ellipsis operator. This operator denotes that any number of argument and various kinds of datatye.
catch(…)
{
}

This catch block will accept the more than one type of argument here. I.e., this catch block will accept integer throw, logical error throw and so on. You you want to define the generic catch statement you can use this one.