Exceptional situation

As part of my C++ journey (not for the first time), I embarked upon "exception handling". After reading the first few paragraphs,  I wanted to get my hands dirty by a code which catches an exception and shots howzzat.

Which exception is easily conceivable that divide by zero? So I cinned two numbers, divided them and waited with bated breath.  And was sadly disappointed. Instead of catching the error, my program crashed. I tried "exception", "Exception", "std::exception".  All IDEs are not android studios to give the correct version and its needed header file. Incidentally I am using Codelite with mingw compiler it suggested - not bad for a windows gcc IDE.

So I had an idea - use catch(...) - which can not fail. It is supposed to catch all exceptions. I thought stupid Windows system is unable to handle exceptions. So rewrote the code in ubuntu. With exactly same results.

So there must be some thing wrong with the code? What can be wrong with 3 line code - try - divide n1 by n2 followed by catch?

Again my memory said I had been here before. So let me just throw an int error

try
{
     if (n2==0) 
          throw 5; 
return n1/n2;
}
catch (int e)
{
 cout<<"Exception";
}
 And voila, the program worked. So the problem is not with exception handling. It is with floating point exception or divide by zero error.

Little googling told me that Stroustrup wanted divide by zero to be handled by low level code like Assembly language, not be exception handling.

Why don't any books mention that? Don't they know that we code - enthusiasts first try with division by zero error.

So now I am telling you. Don't expect, an exception to be thrown or caught when you divide by zero.

Another thing. Instead of throwing int, if you want to throw an exception object, the method is to say throw exception();
     try{  
           if(n2==0) throw exception();  
           return n1/n2;  
      }catch( exception e)  
      {  
           cout<<"there was an error in divide";  
           cout<<e.what();  
      }  

In a few days, I will add another post - this time a serious one, about exception handling.

Comments

Popular Posts