简体   繁体   中英

c++ program with exceptions not working

I've tried to write this simple code in MinGW, but every time i try to set x as a negative number, it shows the message "out of system bounds!!" and it should show "x is lower than 0". I just don't understand why it keeps showing only that message....

    #include <iostream>

    #define Max 80
    #define Min 20

    using namespace std;

    class Punct
    {
protected:
    int x,y;

public:
    class xZero{};
    class xOutOfSystemBounds{};

    Punct (unsigned a, unsigned b)
    {
        x=a;
        y=b;
    }

    unsigned Getx()
    {
        return x;
    }

    unsigned Gety()
    {
        return y;
    }

    void Setx( unsigned a )
    {
        if( a<0 )
            throw xZero();
                else
                if(( a>Max || a<Min ) && a>0 )
                    throw xOutOfSystemBounds();
                    else
                    x=a;
    }

    void Sety( unsigned a )
    {
        if( a<0 )
            throw xZero();
                else
                if( a>Max || a<Min )
                    throw xOutOfSystemBounds();
                    else
                    y=a;
    }
};

int main()
{
    Punct w(4,29);

    try
    {
        w.Setx(-2);
        cout<<"noul x:>"<<w.Getx()<<'\n';
    }

    catch( Punct::xZero )
    {
        cout<<"x is lower than 0"<<'\n';
    }

    catch( Punct::xOutOfSystemBounds )
    {
        cout<<"out of system bounds!!"<<'\n';
    }

    catch( ... )
    {
        cout<<"Expresie necunoscuta!"<<'\n';
    }

    system("PAUSE");
    return 0;
 }

void Setx( unsigned a ) takes argument as unsigned int . When you send a (signed) negative number, it gets converted to unsigned int , and becomes a large positive number (> Max ) . Hence xOutOfSystemBounds exception is thrown, instead of xZero . You have to change

void Setx( int a ){ ...}

That's because you're using an unsigned in your setter arguments which, by definition, has no negative values. Change it to int and it should behave as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM