Exception handling and its classification in C++
Exception Handling: The error handling mechanism of C++ is generally referred to as exception handling. C++ provides a mechanism of handling errors in a program.
Generally exceptions are classified into synchronous and asynchronous exceptions.
- Synchronous Exceptions: The exceptions which occur during the program execution due to some fault in the input data or technique that is not suitable to handle the current class of data, within the program are known as synchronous exceptions. For example: errors such as out of range, overflow, underflow and so on belong to the class of synchronous exceptions.
- Asynchronous Exceptions: The exceptions caused by events or faults unrelated (external) to the program and beyond the control of the program are called asynchronous exceptions. For example: errors such as keyboard interrupts, hardware malfunctions, disk failure and so on belong to the class of asynchronous exceptions.
The exception handling mechanism of C++ is designed to handle only synchronous exceptions within a program.
This is done by throwing an exception. The exception handling mechanism uses three blocks: try, throw and catch. The try-block must be followed immediately by a handler, which is a catch block. If an exception is thrown in the try block, the program control is transferred to the appropriate exception handler. The program should attempt to catch any exception that is thrown by any function. Failure to do so may result in abnormal program termination.
Exception Handling Constructs:
(1) throw:- The keyword throw is used to raise an exception when an error is generated in the computation.
(2) catch:- The exception handler is indicated by the catch keyword. It must be used immediately after the statements marked by the try keyword.
(3) try:- The try keyword defines the boundary within which an exception can occur.
Thus, the error handling code must perform the following tasks:-
- Detect the problem causing exception. (Will hit the exception).
- Inform that an error has occurred. (Throw the exception).
- Receive the error information (Catch the exception).
- Take corrective actions. (Handle the exception).
For example: (Divide operation validation)
int division(int n1, int n2)
{
if(n2==0)
throw n2;
else
return n1/n2;
}
int main()
{
————
————
————
try
{
result=division(n1,n2);
}
catch(int)//exception handler block
{cout<<”Exception raised! Division Error…!”;
return -1;
}
————
————
}