Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused with C++ Exception throw statement

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;    
   }
}
like image 402
user2746926 Avatar asked Aug 09 '16 11:08

user2746926


People also ask

What is throwing an exception in C Plus Plus?

A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch, and throw.

What will happen if a thrown exception is not handled in CPP?

if you don't handle exceptions When an exception occurred, if you don't handle it, the program terminates abruptly and the code past the line that caused the exception will not get executed.

What does throw () mean in C?

In /std:c++17 mode, throw() is an alias for noexcept(true) . In /std:c++17 mode and later, when an exception is thrown from a function declared with any of these specifications, std::terminate is invoked as required by the C++17 standard.

Can you throw exceptions in C?

C doesn't support exceptions. You can try compiling your C code as C++ with Visual Studio or G++ and see if it'll compile as-is. Most C applications will compile as C++ without major changes, and you can then use the try... catch syntax.


1 Answers

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

like image 93
Sam Varshavchik Avatar answered Oct 05 '22 20:10

Sam Varshavchik