Confused with C++ Exception throw statement
Asked Answered
E

1

6

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++.

  • In the below code why do we call a function with name matching the class name?
  • Is it a constructor?
  • Is it creating an instance of 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;    
   }
}
Extract answered 9/8, 2016 at 11:25 Comment(2)
Yes it is creating an instance of Except using the default constructor, which takes no arguments.Wheelock
As you are learning; catch exception by const reference eg catch(const Except & E)Farming
D
7

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).

Daradarach answered 9/8, 2016 at 11:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.