This issue’s topic:
As is well known, in C language, dividing a number by 0 will lead to a division operation exception, causing the program to crash.
To avoid program crashes, we need to include checks for 0 in the code.
However, when running C program code that performs division by zero on STM32 microcontrollers, the program does not crash. Why is that?
Today, let’s briefly discuss this issue.
Discussion:
According to conventional understanding, if a division by zero operation appears in C program code, it will enter exception handling, leading to program exceptions.
Some friends have encountered a scenario where the code following a division by zero operation can execute normally on an STM32 microcontroller.
By consulting the Cortex-M3 guide, we can see that a division by zero operation leads to a Usage Fault.

From this, we can understand that entering a Usage Fault has prerequisites: it only occurs when DIV_0_TRP
is set.
By configuring DIV_0_TRP
, we can enable division by zero exception interrupt capture. This bit register is located in the SCB->CCR
register.
DIV_0_TRP
is 0, and division by zero operations will not produce exceptions, and the result will always be 0; when DIV_0_TRP
is set to 1, it will trigger a division by zero exception interrupt.
Now, we can explain why STM32 microcontrollers do not crash during division by zero operations under default conditions.
Additionally, division by zero triggers a Usage Fault, but by default, the Usage Fault is disabled. In this case, the division by zero exception will enter the Hard Fault exception interrupt.
That’s all for today, thank you for reading!

END
→ Follow for more updates ←