Hi there! Well, the 30 days of code from HackerRank had some challenges that didn’t allow me to use Go and this is one of them. The idea is to create a custom exception and throw it. My choice of language was C++ and the solution is given below. Notice that not all code is mine, the IO handling was given by HackerRank (probably to force me use a class Calculator and an exception haha).

#include <cmath>
#include <iostream>
#include <exception>
#include <stdexcept>
using namespace std;

// ------------- my code ----------
class PowerException : public exception {
virtual const char* what() const throw() {
  return "n and p should be non-negative";
}
} except;

class Calculator {
public:
int power(int n, int p) {
  if (p < 0 || n < 0) {
    throw except;
  }
  return pow(n, p);
}
};
// ----------- end of my code ----------

int main() {
  Calculator myCalculator=Calculator();
  int T,n,p;
  cin>>T;
  while(T-->0) {
    if(scanf("%d %d",&n,&p)==2) {
      try{
        int ans=myCalculator.power(n,p);
        cout<<ans<<endl;
      }
      catch(exception& e) {
        cout<<e.what()<<endl;
      }
    }
  }
}

I actually had some troubles throwing the exception. My first trial was not actually defining an exception but just throwing a message throw "n and p should be non-negative". This gave me the following output

$ ./day_17
1
-1 -2
libc++abi.dylib: terminating with
  uncaught exception of type char const*
[1]    63186 abort      ./day_17

This means that initially I just threw a constant expression instead of an actual class that inherits from exception. I think I did this because I didn’t pay attention to the e.what() code. This means the exception has the method what() and surely a char const* doesn’t have this method. After fixing it, I could run the program as follows:

$ g++ -std=c++11 day_17.cpp -o day_17
$ ./day_17
# input
2 # number of cases
1 3 # case 1
-4 5 # case 2
#output
1
n and p should be non-negative

Virtual Method

A new concept for me in C++ was the one of a virtual method. A virtual method solves the problem of deciding which method runs when there are multiple implementations of it by a base class and its derived classes. In my case, the base class is exception and it has a method called what() declared as virtual. As it is virtual, I can override it in my derived class and then my implementation will be called when I do e.what() even if e is masked by type exception instead of my PowerException class. This way I don’t need to pay attention to the actual exception class, but just override the virtual method of it in the derived class.

Notes

As mentioned in one comment, there are equivalents in Java to virtual methods that I knew about but I didn’t think when writing this post. By default Java classes have only virtual methods, while in C++ the default is non-virtual.

That’s all for this post. Thanks for reading!