Reputation: 71
I am new to C++, so sorry for asking very silly questions but I am confused with the throw statements in Exception Handling mechanism of C++.
class Except
?I am not understanding the syntax there.
class A
{
public:
class Except{};
void foo() { throw Except(); }
};
int main()
{
A a;
try
{
a.foo();
}
catch(Except E)//exception handler
{
cout << "Catched exception" << endl;
}
}
Upvotes: 6
Views: 302
Reputation: 118435
Is it a constructor?
Yes.
Is it creating an instance of Except class ?
Yes again. Both of these statements are true.
classname( arguments )
Where classname
is a name of a class constructs an instance of this class, passing any optional arguments
to the appropriate class constructor.
And, of course, constructors are class methods whose names are the same as the class name. That's why both of your questions have the same answer, "yes".
This creates a temporary instance of a class. Normally the classname
is used to declare a variable that represents an instance of this class, but this syntax constructs a temporary instance of the class, that gets destroyed at the end of the expression (generally). If all that's needed is to pass an instance of the class to another function, a separate variable is not needed (throwing an exception would fall into this category, too).
Upvotes: 7