Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a catch exception-declaration allow trailing parentheses?

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.

like image 963
Greg Hewgill Avatar asked Feb 19 '18 01:02

Greg Hewgill


People also ask

Can we use catch () without passing arguments in it?

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.

Does catching an exception stop execution Java?

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.

Which type of catch block is used to catch all types of exceptions in C++?

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.

What is Java exception E?

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.


1 Answers

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 type T is adjusted to be of type “pointer to T”.

So catch (exception()) is identical to catch (exception(*p)()).

like image 111
Kerrek SB Avatar answered Oct 04 '22 09:10

Kerrek SB