2

I created a C++ library. I am using it in an iOS application. I thought of handling exceptions in C++ library and in order to test this I created a test scheme and called the c++ function from it. In the c++ function I intentionally wrote erroneous code.

try 
{
    int i = 0;
    int j = 10/i;
} 
catch(std::exception &e){
    printf("Exception : %s\n",e.what());
}

But the exception is never caught and the application breaks at - int j = 10/i;

Please tell me, how can I add exception handling to my c++ code in this scenario?

Thanks.

Any
  • 168
  • 3
  • 11

1 Answers1

2

C++ doesn't throw an exception when a division by zero is encountered (see also this and this other questions)! Quoting Stroustrup:

low-level events, such as arithmetic overflows and divide by zero, are assumed to be handled by a dedicated lower-level mechanism rather than by exceptions. This enables C++ to match the behaviour of other languages when it comes to arithmetic. It also avoids the problems that occur on heavily pipelined architectures where events such as divide by zero are asynchronous.

"The Design and Evolution of C++" (Addison Wesley, 1994)

So you will have to handle this case yourself - you'll have to check each potential divisor before division and handle it.

Community
  • 1
  • 1
codeling
  • 11,056
  • 4
  • 42
  • 71