Reputation: 125
I recently interviewed with a company for an internship. They asked me to write a recursive function to calculate factorial of a given integer. So I wrote something like this, on paper:
int factorial(int n){
if(n<0){throw std::invalid_argument( "received negative value" );}
if(n == 0){return 1;}
else{
return n * factorial(n-1);
}
}
Then as a follow-up, they asked me questions along the lines of
"What onus does throwing an exception put on the user of this function?"
"Can you handle this in any other way?"
"Can you handle it gracefully?"
I really didn't know what they were looking for/were hinting at. Can anyone tell me if I am missing something here?
Upvotes: 3
Views: 405
Reputation: 6418
The requirement to check for an exception requires the caller to trap and handle the exception, cluttering their code and also imposing a processing overhead to handling the exception.
There are some other ways you can return without raising an exception.
int
, you can return this invalid value as well, or set the specific value to something that indicates the failure mode (e.g. 0 means input negative, -1 means input too large, -2 means any other exception).int
, and set the logic to return NULL
to indicate no result (C code was classically filled with "check for null after the call to make sure it succeeded" logic). If you find the factorial, return a pointer to an int
holding that value, created on the heap using new
.short int
as the input parameter, eliminating many (but not all) input values whose factorial is too large to fit the return value. This won't fix things completely, but every bit helps. Combined with another method, you can reduce potential failure modes even further.The first option above can be graceful, since it allows the caller to consume the value in many ways (e.g. printing it, using it in a further math operation) without feeding in something that is non-numeric or failing to have a number to deal with. The downside is that you can end up with a meaningless number. It's better in some contexts to output "Number of floors in building: -1, Cost: $-1" than to crash right in the middle of an important demo! A similar situation (invalid in terms of business rules but able to be processed data, in that case a pointer) produced the famous Minus World bug in Super Mario Bros.!
The last value is even more graceful, since it helps prevent invalid data from even getting to the function. As they say, Garbage In, Garbage Out.
Upvotes: 3