Monday, February 1, 2010

EXCEPTION HANDLING C++

Exceptions provide a way to react to exceptional circumstances (like runtime errors) in our program by transferring control to special functions called handlers.

To catch exceptions we must place a portion of code under exception inspection. This is done by enclosing that portion of code in a try block. When an exceptional circumstance arises within that block, an exception is thrown that transfers the control to the exception handler. If no exception is thrown, the code continues normally and all handlers are ignored.





NOTE: While handling derived class exception its required to first catch the derived class object before the base class otherwise the code under the derived class catch will never be executed.


Example:


#include < iostream >
using namespace std;


class B{
};


class D: public B {
};


int main()
{
 D derived;
 try {
 throw derived;
 }
 catch ( B b) {
cout<< "caught a base exception";
}
catch (D d) {
cout << "caught a derived exception";
}
return 0;
}


Here the catch(D d) will never be executed as the exception will flow to the catch(B b).


A exception is thrown by using the throw keyword from inside the try block. Exception handlers are declared with the keyword catch, which must be placed immediately after the try block:



Example



// exceptions
#include < iostream >
using namespace std;

int main () {
  try
  {
    throw 20;
  }
  catch (int e)
  {
    cout << "An exception occurred. Exception Nr. " << e << endl;
  }
  return 0;
}


For example, if we use the operator new and the memory cannot be allocated, an exception of type bad_alloc is thrown:



try
{
  int * myarray= new int[1000];
}
catch (bad_alloc&)
{
  cout << "Error allocating memory." << endl;
}


Because bad_alloc is derived from the standard base class exception, we can handle that same exception by catching references to the exception class:



// bad_alloc standard exception
#include < iostream >
#include < exception >
using namespace std;

int main () {
  try
  {
    int* myarray= new int[1000];
  }
  catch (exception& e)
  {
    cout << "Standard exception: " << e.what() << endl;
  }
  return 0;
}



In real world scenario we mostly have an exception class, which tells what the exception is.

Example:

#include < iostream >
#include < cstring >
using namespace std;

class MyException{

public:
char str_what[80];
int what;
MyException{
*str_what = 0;
what=0;
}
MyException(char *s, int i){
strcpy(str_what, s);
what = i;
}
};
int main()
{
int i;
try {
cout << "Enter a positive number:  ";
cin >> i;
if(i<0)
throw MyException("Not Positive",i);
}
catch (MyException e){
cout<< e.str_what << " : ";
cout<<  e.what << "\n";
}
return 0;
}
If Enter a positive number: -4
Not Positive: -4


No comments:

Post a Comment