Microsoft Interview Question
Country: United States
Thanks, it works
one more question
The routine 'myfunc' is designed to throw an exception of type 'myExcep'. However it is being called from the 'main' function assuming that an exception of type 'derivedExcep' will be caught. Correct the code so that the exception thrown by the 'myfunc' function is caught and handled by the catch block in the 'main' function. The routine 'my_handler' should be helpful to you.
#include <iostream>
#include <exception>
class myExcep {
public:
myExcep () {}
};
void myfunc() throw (myExcep) {
throw 0;
}
class derivedExcep : public myExcep {};
//changes allowed in below code only
void my_handler() throw (&derivedExcep) {
std::cout<< "hit the handler" << std::endl;
throw derivedExcep();
}
int main() {
try {
myfunc();
}
catch (derivedExcep & e) {
std::cout<<"caught exception gracefully"<< std::endl;
}
return 0;
}
Can you please explain whats wrong with the code.. is it the increment in the get_val() function ?
//some mistake was there in above code
#include <iostream>
#include <exception>
class myExcep {
public:
myExcep () {}
};
void myfunc() throw (myExcep) {
throw 0;
}
class derivedExcep : public myExcep {};
//changes allowed in below code only
void my_handler() throw (&derivedExcep) {
std::cout<< "hit the handler" << std::endl;
throw derivedExcep();
}
int main() {
try {
myfunc();
}
catch (derivedExcep & e) {
std::cout<<"caught exception gracefully"<< std::endl;
}
return 0;
}
mutable int num;
- Vikrant October 02, 2012