Pretty confused about C++ Exception Handling

Viewed 346

Trying to add exception handling to my C++ program, but I find it pretty confusing. The program sets the values i and j to their highest possible values and increments them. I think I want the exception handling to detect the integer overflow / wraparound when it happens(?)

So far this is what I've got:

#include <iostream>
#include <limits.h>
#include <exception>
#include <stdexcept>
using namespace std;

int main() {
    int i;
    unsigned int j;

    try{
            i = INT_MAX;
            i++;
            cout<<i;
    }
    catch( const std::exception& e){
    cout<<"Exception Error!";
    }   


    try{
            j = UINT_MAX;
            j++;
            cout<<j;
    }
    catch(const std::exception& e){
    cout<<"Exception Error!";
    }
}

The program runs, but the exception handling part doesn't work.

What could be the issue?

3 Answers

Well the behaviour of incrementing i beyond INT_MAX is undefined. That's because it's a signed integral type. I've never come across an implementation that throws an exception in this case. (Typical behaviour is wrap-around to INT_MIN but don't rely on that.)

Incrementing j beyond UINT_MAX must wrap-around to 0. That's because it's an unsigned type. That is, an exception must never be thrown.

C++ does not define any exceptions to be thrown in case of integer overflow. If you want to achive such behavior you will need some wrapper for integer class with corresponding functionality, such as Safe Int library. Example:

#include <safeint.h>

#include <iostream>

int main()
{
    try
    {
        ::msl::utilities::SafeInt<int> j;
        for(;;)
        {
            ++j;
        }
    }
    catch(::msl::utilities::SafeIntException const & exception)
    {
        switch(exception.m_code)
        {
            case ::msl::utilities::SafeIntArithmeticOverflow:
            {
                ::std::cout << "overflow detected" << ::std::endl;
                break;
            }
            default:
            {
                break;
            }
        }
    }
    return(0);
}

In C++, exceptions don’t just happen. Exceptions are thrown by the throw keyword; if your code (or code you’ve linked to) doesn’t have throw something() it doesn’t throw exceptions.

That’s not quite true, however: there are funky situations where the code does something inappropriate (formally, the code has undefined behavior), which might result in an exception being thrown. That’s outside the rules of the language definition, so not portable and not reliable (yes, I’m looking at you, Windows SEH).

Related