I have come across some C++ code that looks like the following:
class exception {};
int main()
{
try {
throw exception();
} catch (exception()) {
// ...
}
}
Note the extra set of parentheses in catch (exception())
. According to Compiler Explorer, this is compiled to the same object code as if it were written with catch (exception &)
.
On what basis is the extra set of parentheses permitted, and what part of the standard allows this? As far as I was aware, a catch
clause requires a type specifier, but exception()
doesn't seem like a type specifier.
You can also omit the arguments on the catch block entirely. In this case, the catch block will catch all exceptions, regardless of their type. Because you don't declare an exception variable, however, you won't have access to information about the exception.
All methods in the call stack between the method throwing the exception and the method catching it have their execution stopped at the point in the code where the exception is thrown or propagated.
We can use try catch block to protect the code. Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions.
e is a reference to the instance of the Exception , like s would be a reference to an instance of String when you declare like String s = "..."; . Otherwise you won't be able to reference the exception and learn what's wrong with your code.
Exception handler declarations work like function declarations, in that array and function type parameters are adjusted to pointers. (That is, arrays and functions cannot be thrown or caught "by value".) Specifically, [except.handle]p2 says:
A handler of type “array of
T
” or function typeT
is adjusted to be of type “pointer toT
”.
So catch (exception())
is identical to catch (exception(*p)())
.
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