Inherited Code Discussions | C++ | HackerRank

Inherited Code

  • + 43 comments

    I had never done anything with exceptions before so I found this one quite confusing, especially since it doesn't specify that you are supposed to create a new class. For anyone else wondering,

    BadLengthException(n)
    

    is a class constructor, not just an external function. The variable "e" is an object of this class, and "what()" is a function inside the class.

    For anyone else unfamiliar with exceptions, an exception consists of a "throw" and a "catch". A "throw" is followed by an object or variable. When the "throw" is called, the program will jump to the "catch" using said object/variable as an input to the catch. In this case, the throw constructs a new object of class "BadLengthException", which is then used as the input to the catch (this is labelled as "e").

    The code that I used is as follows:

    /* Define the exception here */
    class BadLengthException {
        private: 
            int n;
        public:
            BadLengthException(int errornumber) {
                n = errornumber;
            }
        
            int what() {
                return n;
            }
    };