Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error processing : return value vs exception in C++

In the course of asking about catching 'divide by 0' exception, I found that with C++, we can't do that. I mean, divide by 0 doesn't throw an std::exception.

Some of the hints that I found were I have to check the value, and throw the exception by self.

I say it's confusing, as I've thought that C++ adopted the exception idea in order to replace the 'good old C/UNIX report error by returning value method'.

Here are my questions

  • Q1 : Why C++ doesn't throw std::exception error for divide by 0? Is there any reason behind that?
  • Q2 : Normally, what error processing scheme the C++ users use? Always throw an error, and the exception is the divide by 0 error?
  • Q3 : In general, OOP languages prefer (or even enforce) using exception. Is this correct?
like image 282
prosseek Avatar asked Jun 24 '10 21:06

prosseek


1 Answers

C++ assumes you know what you're doing, doesn't pay for things you don't ask for, and makes no assumptions about the platforms it's intended for.

If you want to divide numbers, it would be quite inefficient to mandate the compiler check the denominator and throw before dividing. (We didn't ask it to do that.) So that option is out; we can't have this check on every division, and it's especially wasteful since most divisions are not by zero.

So, how can we just divide by zero and find out if it worked? Because C++ cannot assume anything about it's platform, it cannot assume there is a way to check the result, hardware-wise. That is to say, while many CPU's will jump to an interrupt of some sort when division by zero occurs, the C++ language cannot guarantee such a thing.

The only option then is to let the behavior be undefined. And that's exactly what you get: undefined behavior.


OOP languages might do something or another, it doesn't matter since OOP isn't well-defined and C++ isn't an OOP language anyway. In general, use the tool that's most appropriate. (Exceptions are for exceptional situations.)

like image 100
GManNickG Avatar answered Oct 02 '22 12:10

GManNickG