Thought Sharing

Monday, June 10, 2013

Exceptions/ Exception Handling in C++

An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero or infinite loop etc.
Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch, and throw.

  •     throw: A program throws an exception when a problem shows up. This is done using a throw keyword.
  •      catch: A proram catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
  •      try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks.

Assuming a block will raise and exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:

ALGORITHM:

Step 1: Start the program.
Step 2: Declare the variables a,b,c.
Step 3: Read the values a,b,c,.
Step 4: Inside the try block check the condition.
            a. if(a-b!=0) then calculate the value of d and display.
            b. otherwise throw the exception.
Step 5: Catch the exception and display the appropriate message.
Step 6: Stop the program.

PROGRAM:

#include
#include
void main()
{
   int a,b,c;
   float  d;
   clrscr();
   cout<<"Enter the value of a:";
   cin>>a;
   cout<<"Enter the value of b:";
   cin>>b;
   cout<<"Enter the value of c:";
   cin>>c;
   
   try
   {
              If ((a-b) != 0)
              {
                 d=c/(a-b);
                 cout<<"Result is:"<
              }
              else
              {
                 throw(a-b);
              }
   }

   Catch (int i)
   {
              cout<<"Answer is infinite because a-b is:"<
   }
     getch();
}

Output:

              Enter the value for a: 20
              Enter the value for b: 20
              Enter the value for c: 40
             Answer is infinite because a-b is: 0