Throw and catch std :: string

I made weird code, but surprisingly it works. But now I don’t know what I am throwing, and how to catch him:

class Date {
private:
    int day;
    int month;
    int year;
    int daysPerMonth[];
public:
    Date( int day, int month, int year ) {
        int daysPerMonth[12] = {31,28,31,30,31,30,31,31,30,31,30,31};

        if(isValidDate(day, month, year)) {
            this->day = day;
            this->month = month;
            this->year = year;
        } else {
            throw std::string("No valid input date numbers...");//what i throw???
        }
    }

Please help me with the code.

+4
source share
3 answers

You can use As shown below (Not compiled): -

class Date {
private:
int day;
int month;
int year;
int daysPerMonth[];
public:
Date( int day, int month, int year ) {
    int daysPerMonth[12] = {31,28,31,30,31,30,31,31,30,31,30,31};

    if(isValidDate(day, month, year)) 
    {
        this->day = day;
        this->month = month;
        this->year = year;
    } else {
        throw std::string("No valid input date numbers...");//what i throw???
        }
    }
};

int main()
{
 try{
    Date d(55,223,0122);
  }
 catch(std::string &e)
 {
    // Do necessary handling
  }
}
+2
source

In C ++, you can throw objects of any type. This is usually std::exceptionor a type derived from it, but it can be anything. For example, CExceptionin MFC or _com_errorhas nothing to do with std::exception. No matter what you throw, you have to catch the same thing. (You cannot throw std::stringand catch std::exception.)

+2

++ throw ( ).

try {
    throw 42;
} catch(int e) {
    std::cout << "Caught: " << e << "\n";
}

, ++, , , , .

, - std::exception. , , , . , , , , .

, , : , std::exception; , .

Such exception hierarchies are much easier to maintain and reason about whether you save exception types different from other types used in your program. In addition, this guide makes it less attractive for people to abuse exceptions as glorified return values, which you should never do.

+1
source

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


All Articles