0

When you try to divide a number by zero, the Operating System should pull up an interrupt (as I know).

My question was related to this topic: when you try to divide a number by zero with the calculator of windows is the program that intercepts the exception, or is the OS that opens an interrupt of a system that drops an exception which is resolved by the program?

krmogi
  • 2,588
  • 1
  • 10
  • 26
Zenek
  • 110
  • 1
  • 4
  • 12

1 Answers1

1

TLDR Since Windows is a closed-source operating system, I personally can't verify Windows kernel behavior, but my educated guess is that the program checks for divide by zero before letting your calculation go through to the CPU/ALU.


In general, you're right, if divide by zero makes it all the way to the CPU/ALU, then an exception/interrupt should be generated. As explained here, in Linux, that exception will end up sending a kill signal SIGFPE to the user-level process.

You can verify this in Linux by compiling this program:

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

Running gcc test.c already warns you about divide by zero, but let's you continue if you wish:

test.c: In function ‘main’:
test.c:2:14: warning: division by zero [-Wdiv-by-zero]
    2 |     int x = 1/0;
      |              ^

Once you run it, you get an error saying Floating point exception (core dumped) which is what SIGFPE is.

Now let's look at the behavior of the Windows calculator. When you divide by zero it shows the error Cannot divide by zero. The key is, the calculator program doesn't crash, you can continue doing calculations. Assuming Windows functions like Linux, it's most likely that the calculator does a "divide by zero" check before running your calculations on the CPU, allowing it to catch the error before the OS can get involved.

wxz
  • 2,254
  • 1
  • 10
  • 31
  • 1
    Thank you! Really nice explanation. Also really interesting the Linux's part about the interrupt. By the way, even if the OS is not called in windows, that exception should be resolved in some way ... maybe the program calls the OS anyways? – Zenek Apr 14 '21 at 22:01
  • 1
    I don't think so. The error is resolved when it prints `Cannot divide by zero` to screen and then you the user can continue typing numbers. Why get the OS involved when you can handle the exception at user-level? – wxz Apr 14 '21 at 22:04
  • yea... you right ... don't thought about drop the exception and resolve it in user level! – Zenek Apr 14 '21 at 22:05