0

I am taking a course online and came across some syntax I am not really sure I understand.

    #include <iostream>
    #include <exception>

    using namespace std;

    class derivedexception: public exception {
          virtual const char* what() const throw() {
            return "My derived exception";
  }        
    } myderivedexception;

    int main() {
          try {
            throw myderivedexception;
          }
          catch (exception& e) {
            cout << e.what() << '\n';
          }
    }

My Problem is with:

    virtual const char* what() const throw() 

What does this line mean?

also, what is with the

    } myderivedexception;

in the end of the class declaration?

Praetorian
  • 106,671
  • 19
  • 240
  • 328
kaptsea
  • 113
  • 2
  • 11
  • 1
    Please have a look at this [C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) list. – Ron Mar 18 '18 at 18:11
  • 1
    You'd probably be much better served reading a [C++ book](https://stackoverflow.com/q/388242/241631) for beginners. If this course is showing you the code above without first introducing you to inheritance and virtual functions, it doesn't sound like a good course. – Praetorian Mar 18 '18 at 18:11
  • Not catching the exception by `const&` is also strange. What are you going to do with that non-const reference? Modify the exception after it's been caught? That doesn't make sense. Neither does creating the `myderivedexception` object. Forget about this course. – Christian Hackl Mar 18 '18 at 20:08

1 Answers1

4

This line:

  virtual const char* what() const throw() 

says that what is a virtual method that returns a pointer to a constant char (which means it can be used to return a string literal, or the contents of a std::string obtained by calling the string::c_str() function), is itself constant so it doesn't modify any class members, and it does not throw any exceptions.

This line:

   } myderivedexception;

creates an instance of the derivedexception class named myderivedexception. You probably do not want to do this, but instead throw an unnamed exception:

throw derivedexception();
  • Got a question about the `virtual`. Is it really needed? Isn't this already the override for the `what` method contained within `std::exception `? – Bee Mar 18 '18 at 18:17
  • 3
    No, it's not needed, using it this situation is really a question of style - some people like it. –  Mar 18 '18 at 18:19
  • Ok, so the throw() part means that it does not throw any exceptions? Is there any depth on this? Could you initiate an object in the end of the class declaration as a "default" object? – kaptsea Mar 18 '18 at 18:32
  • 1
    "Ok, so the throw() part means that it does not throw any exceptions? " - yes.Why would you want a "default object"? –  Mar 18 '18 at 18:34
  • Tbh, I don't, the lecturer for some weird reason decided to, plus he did not even care to explain why – kaptsea Mar 18 '18 at 18:50