How to catch the integer division-by-zero exception in C language?

前端 未结 2 1460
心在旅途
心在旅途 2020-12-11 05:06

It is known how to catch the float division-by-zero exception with the usage of

signal(SIGFPE, handler)

but it doesn\'t catch integer divis

相关标签:
2条回答
  • 2020-12-11 05:18

    Division by zero leads to undefined behavior, there is no C language construct that can do anything about it. Your best bet is to not divide by zero in the first place, by checking the denominator.

    If you want to "catch" (note, C has no exceptions) this error, it will be dependent on your compiler and OS, which you haven't listed. By the way, _control87 has only to do with floating-point operations, and nothing to do with integer operations.

    0 讨论(0)
  • 2020-12-11 05:21

    Check what you are dividing against...?

    // if below = 0 then do not divide, just put answer as zero
    
    if (below == 0) {
      result = 0;
    } else {
      result = above/below;
    }
    
    0 讨论(0)
提交回复
热议问题