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;
}
}
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With