LKBEN11204: Why C++ does not catch a divide-by-zero exception


This article has not been checked!

LKB | Created: 02/04/2020 | Version: 0 | Language: EN | Rating: 0 | Outdated: False | Marked for deletion: False

Author: Wim Peeters - Keskon GmbH & Co. KG


Symptom

A divide by zero does not go into my catch block but kills the application

Cause

This is by design.

Solution

In C++ it was a design decision not to handle the divide-by-zero exception in contrast to some other languages like e.g. java. The language C++ tends to be used with more awareness of the hardware compared to other programming languages. Also low level events such as arithmetic overflows are assumed to be handled by a dedicated lower-level mechanism. To handle these errors, you must write code by yourself. This means that a division by zero is not catched by a

catch (...) { }

statement which normally catches all unhandled exceptions.

//a click on the button does not reach the catch, the program will be killed
void CExceptionTestDlg::OnBnClickedButton1()
{
    //Generate handled Exception
    int i = 100;
    int j = 0;
    double k;

    try
    {
        //Generate a division by zero exception (this is not an exception but an error!)
        k = i/j;
    }
    catch (...) // Handle all exceptions
    {
        //and catch it here! (which will not function because there was no exception!)
        int msgboxID = MessageBoxW((LPCWSTR)L"Exception handled.",
            (LPCWSTR)L"Exception handled.",
            MB_ICONWARNING | MB_OK);
    }
}

To handle a division by zero, you check the divisor by yourself and throw an own generated exception.

Conclusion: floating point and division by zero exceptions are not caught by a general catch(...) block.

About the Author

Wim Peeters is electronics engineer with an additional master in IT and over 30 years of experience including time spent in support, development, consulting, training and database administration. Wim has worked with SQL Server since version 6.5. He has developed in C/C++, Java and C# on Windows and Linux in different European countries and different European languages. He writes knowledge base articles to solve IT problems and publishes them on the Lubby Knowledge Platform where he is one of the most important contributors and the main developer.

Disclaimer:

The information provided in this document is intended for your information only. Lubby makes no claims to the validity of this information. Use of this information is at own risk!