Saturday 23 March 2013

Exception handling in C

Exception handling provides us a special type of facility in C.It handles the run-time errors occurred in the program.In the large programs it is very difficult to handle these type of exceptions.Some minor mistakes like divide by zero can create and interrupt in execution of a large program.So it is very difficult to find these smaller problems in a many thousand lines code.So to escape from these problems we use exception handling.There are following four keywords used in exception handling in C:-

  1. __try
  2. __finally
  3. __except
  4. __leave
1)__try :-__tyr is a keyword in C which is used in __try-__finally and __try-__except statemnt.A part of program in which there is chance of exception occurring that part of program write into this part.

2)__leave:-The __leave keyword is valid within a __try -__finally statement it jump to the end of try-finally.The termination handler is executed .Here __leave keyword jump the control to the finally when an exception is occur.We can seen it from this program:
3)__finally:-__finally gives a guarantee execution of a portion of a program when execution of a block code is interrupted.

int a=10,b=0;
__try
{
if (b == 0)
{
__leave;
}
c=(a/b);
cout<<"c="<<c;
}
__finally
{

cout<<"program terminates now";
}

4)__except:-_It is used in __try-__except statement .It is use as exception handler .It uses filter to catch the exception.If an exception occurs during execution of the guarded section or in any routine the guarded section calls, the __except expression (called the filter expression) is evaluated and the value determines how the exception is handled. There are three values:


EXCEPTION_CONTINUE_EXECUTION (–1)   Exception is dismissed. Continue execution at the point where the exception occurred.
EXCEPTION_CONTINUE_SEARCH (0)   Exception is not recognized. Continue to search up the stack for a handler, first for containing try-except statements, then for handlers with the next highest precedence.
EXCEPTION_EXECUTE_HANDLER (1)   Exception is recognized. Transfer control to the exception handler by executing the __except compound statement, then continue execution after the __except block.


It is used in following way:-


int* p = 0x00000000;
__try
{
__try
{
puts("Exception occured");
*p = 13;
//c=(a/b);
}

__finally
{
printf("%s","In finally ...exception handler");
}

}

 __except(filter(GetExceptionCode()))
{
puts("in except");
    }


//

int filter(unsigned int code)
//int filter(unsigned int code, struct _EXCEPTION_POINTERS *ep)
{

   puts("in filter.");

   if (code == EXCEPTION_ACCESS_VIOLATION || code ==STATUS_INTEGER_DIVIDE_BY_ZERO)
   {

      puts("caught AV as expected.");

      return EXCEPTION_EXECUTE_HANDLER;

   }

   else
   {

      puts("didn't catch AV, unexpected.");

      return EXCEPTION_CONTINUE_SEARCH;

   }

}

No comments:

Post a Comment