Pretty confusing in C ++ Exception Handling

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

So far this is what I have:

#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 starts, but part of the exception handling does not work.

What could be the problem?

+4
source share
3 answers

, i INT_MAX undefined. , . , . ( - INT_MIN, .)

j UINT_MAX 0. , unsigned. .

+6

++ , . , , Safe Int library. :

#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);
}
+3

In C ++, exceptions do not just happen. Exceptions selected by keyword throw; if your code (or the code associated with it) does not throw something(), it does not throw an exception.

However, this is not entirely true: there are cases when the code does something inappropriate (formally, the code has undefined behavior), which can lead to the generation of an exception. This is outside the rules of language definition, so it is not portable and unreliable (yes, I look at you, Windows SEH).
0
source

Source: https://habr.com/ru/post/1686863/


All Articles