A Program mainly has two type of errors: logical errors and syntactic errors.
The logical errors occur due to poor understanding of
problem and syntactic errors arise due to poor understanding of language. These errors can be detected by debugging and testing procedures.
There are some problems called Exceptions that are run time anomalies or unusual conditions that a program may encounter while executing.
These anomalies can be division by zero, access to an array outside of its bounds or running out of memory or disk space. When a program encounters an exceptional condition it is important to identify it and dealt with it effectively.
An exception is an object that is sent from the part
of the program where an error occurs to that part of program which is going to
control the error.
Exception Handling
The purpose of exception handling mechanism is to
detect and report an exceptional circumstance so that appropriate action can be
taken.
The mechanism for exception handling is
1. Find the problem (hit the exception).
2. Inform that an error has occurred (throw the
exception).
3. Receive the error information (Catch the
exception).
4. Take corrective actions (Handle the exception).
The error handling code mainly consists of two
segments:
1. To detect error and throw exceptions and
2. To catch the exceptions and to take appropriate
actions.
C++ exception handling mechanism is basically built
upon three keywords:
try, throw and catch.
The keyword try is used to preface a block of
statements which may generate exceptions. This block of statement is called try
block. When an exception is detected it is thrown using throw statement in the
try block.
A catch block defined by the keyword catch ‘catches’
the exception thrown by the throw statement in the try block and handles it
appropriately. The catch block that catches an exception must immediately
follow the try block that throws the exception.
The general form for this is
……………….// program code
………………..
try
{
…………
………… //block of statements which detects and throw an exceptions
throw exception;
…………….
…………….
}
catch(type arg) //catches exceptions
{
…………… // Block of statements that handles the
exceptions
………………
…………….
}
………….// remaining program code
…………..
Example: Division by zero exception handling
#include<iostream.h>
void main()
{
int a,b;
cout<<”enter the values of a and b”;
cin>>a;
cin>>b;
int x = a- b;
try
{
if(x!=0)
{
cout<<”result(a/x) = “<<a/x<<”\n”;
}
else
{
throw(x);
}
}
catch(int i)
{
cout<<”exception caught : x =
“<<x<<”\n”;
}
cout<<”end”;
}
The point at which the throw is executed is called
throw point. Once an exception is thrown to catch block, control cannot return
to the throw point.
No comments:
Post a Comment