Wednesday 9 December 2009

Catching the 'Divide By Zero' exceptions

I was surprised to find that C++ does not catch divide by 0 exceptions by default. The code will crash when a divide by 0 situation occurs. As a result the only option is to write our own class or method to handle divide by 0 scenario. The example below shows how to handle the Divide by zero scenario and how to construct an exception.







//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

class
Division
{

public
:
double
quotient(int numerator, int denominator);
private
:

};


double
Division::quotient(int numerator, int denominator)
{

if
(!denominator)
{

exception e("Divide by 0 exception");
throw
(e);
}

return
(static_cast< double >( numerator ))/denominator;
}



int
main()
{

Division d;
try

{

cout<<"1. (100/10) = "<<d.quotient(100, 10)<<endl;
cout<<"2. (10/4) = "<<d.quotient(10, 4)<<endl;
cout<<"3. (10/0) = "<<d.quotient(10, 0)<<endl;
cout<<"4. (30/9) = "<<d.quotient(30, 9)<<endl;
}

catch
(exception& e)
{

cout<<"Exception caught with cause :"<<e.what()<<endl;
}

return
0;
}








The output is as follows:


You can read more on this topic here.

No comments:

Post a Comment