I’m trying to understand exceptions for my C++ class, and there is something that I don’t understand about this program. Why is there no object created in the exception? Why is there only the class name and parameters provided?
Here: throw( testing ("testing this message"));
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
class testing: public runtime_error
{
public:
testing(const string &message)
:runtime_error(message) {}
};
int main()
{
try {
throw( testing ("testing this message"));
}
catch (runtime_error &exception) {
cerr << exception.what() << endl;
}
return 0;
}
You’re creating a temporary
testingobject. I know the syntax looks a little funny because it’s unnamed. You were expecting to seetesting myObj("Testing this message");, but what you get is the same thing without the variable name.Put a breakpoint in your
testingconstructor and you’ll see you really are creating an object. It just doesn’t have a name in the scope you created it.You can do this in a number of places (
throws,returns, and as arguments to functions)…