user1202733 user1202733 - 1 month ago 10
C++ Question

Why does GCC report a Floating Point Exception when I execute 1/0?

Stroustrup says, in "The Design and Evolution of C++" (Addison Wesley, 1994), "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."

Q1: If it's not an exception, why does GCC report one as opposed to a lower-level error?

Q2: Given I'm dividing integers, why is it reported as floating point ?

Given I cannot catch it with catch(...), it is very misleading. Obviously I can test and avoid the whole 'error', but my point is that it is very confusing for a beginner who thinks that it might be an exception (reasonable), tries to catch it , then finds out that it's NOT AN EXCEPTION , and wonders about the run-time exception reported.

My compiler is gcc version 4.2.1 (Apple Inc. build 5666) (dot 3)

Some accurate clarification of the difference between CPU exceptions, FPU exceptions, Language exceptions and OS exceptions might resolve this.

Example Program:

int main(){
int i=1/0;
return i;
}


Resulting Output:


Floating point exception

Answer

A floating-point exception (FPE) is not a C++ exception. There are several types of exceptions in various systems, and they are not interchangeable. An FPE is an exception at the microprocessor or ISA level, but not at the C++ level. An FPE may result in the firing of a signal called SIGFPE, which you can handle but not using C++ try/catch. If you want to handle it you can use the POSIX function sigaction (I think on Windows one would use Structured Exception Handling).