3

i have this test code to handle exceptions in constructors. function f() create an exception division by zero but this exception does not caught. Instead if i throw a custom integer the exception is caught.

#include <iostream>
using namespace std;

class A
{
public:
  void f(){
    int x;
    x=1/0;
    //throw 10;
  }

 A(){
   try{
     f();
     }
     catch(int e){
       cout << "Exception caught\n";
       }
   }
 };

int main (int argc, const char * argv[])
{

   A a;
  return 0;
}

why i can catch the custom throw 10; and not the x=1/0;

demosthenes
  • 1,151
  • 1
  • 13
  • 17

2 Answers2

7

An Integer divided by zero is not an standard C++ exception. So You just cannot rely on an exception being thrown implicitly. An particular compiler might map the divide by zero to some kind of an exception(You will need to check the compiler documentation for this), if so you can catch that particular exception. However, note that this is not portable behavior and will not work for all compilers.

Best you can do is to check the error condition(divisor equals zero) yourself and throw an exception explicitly.

class A
{
    public:
         void f()
         {
             int x;
             //For illustration only
             int a = 0;
             if(a == 0)
                  throw std::runtime_error( "Divide by zero Exception"); 
             x=1/a;
         }

         A()
         {
              try
              {
                   f();
              }
              catch(const std::runtime_error& e)
              {
                   cout << "Exception caught\n";
                   cout << e.what(); 
              }
         }
 }; 
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • Note that with integer division by zero, *anything* can happen, including a crash, nasal demons and the programmer getting pregnant. –  May 05 '12 at 10:36
4

A division by zero is not a C++ exception.

Have a look at the answers there: C++ : Catch a divide by zero error and also C++'s (non-)handline of division by zero.

Community
  • 1
  • 1
Gregory Pakosz
  • 69,011
  • 20
  • 139
  • 164