C ++ with and without throw () in method / constructor signature for custom exception

I start in C ++ and therefore apologize for this stupid question. I post it here because I cannot find a similar answer in stackoverflow.

I dealt with exceptions in C ++, and since I dealt with some custom exceptions, I have this code

class MyException: public std::exception{
public:
    virtual const char* what() const throw() {
        return "something bad happened";
    }

};

// class that throws above exception

class canGoWrong {
public:
    canGoWrong(){
        throw MyException();
    }
};

The above code was shown by the teacher. The constructor has just implemented a virtual function defined in the base class exception. I got to him.

Now, when I tried to use a different version for practice, I tried to use a user-defined function instead of overriding the virtual one (since C ++ does not strictly abide by the concept of the interface, please correct me if I am wrong here.)

I wrote it as

class my_custom_shit_exception: public std::exception {
public:
    const char* show() { // I omitted the const throw() here
            return "This is an error encountered\n";
    }
};

class myclass {
public:
    myclass() {
        throw my_custom_shit_exception();
    }
};

, .

public:
const char* show() {
        return "This is an error encountered\n";
}
virtual const char* what() const throw() {
    return "something bad happened";
}
  • , const throw() what()? ?

.

+6
2

class std::exception {
    //...
public:
    virtual const char* what() const throw();
    //...
};

: what - std::exception, () (, const) .

, : , ++ 11 noexcept , "" . , ++ 17 throw() noexcept(true), .

. noexcept.

: " , noexcept , , . , [...]".

+3

Scott Meyers

" ++"

int doSomething() throw(); // note empty exception spec.

, doSomething ; , doSomething , , . †

. ++. (, , set_unexpected, , .)

" ++"

++ 11 noexcept .

f, fs . ++ 98, fs , , , . ++ 11 : . , , . noexcept , , , noexcept , . "throw()" , .

+4

All Articles