Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any use for C++ throw decoration?

Tags:

c++

exception

I've started using C++ exceptions in a uniform manner, and now I'd like the compiler (g++) to check that there are no "exception leaks". The throw decoration should do this, like const does for constness of class methods.

Well, it doesn't.

Using throw is still documentary, but may even be dangerously misleading if others think a function cannot throw other exceptions than those listed in its documentation.

Can g++ somehow be persuaded to be more strict on its throw-checking, i.e. really making sure a function decorated as throw() will never-ever throw anything.

Edit: Found this question handling the subject widely.

like image 850
akauppi Avatar asked Sep 11 '09 10:09

akauppi


People also ask

What is throw in C++?

The throw keyword throws an exception when a problem is detected, which lets us create a custom error. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

When exception specification is used?

An exception specification is not part of a function's type. An exception specification may only appear at the end of the top-level function declarator in a declaration or definition of a function, pointer to function, reference to function, or pointer to member function.

What happens if an exception is thrown but not caught C++?

The other exceptions, which are thrown but not caught, can be handled by the caller. If the caller chooses not to catch them, then the exceptions are handled by the caller of the caller. In C++, a function can specify the exceptions that it throws using the throw keyword.

How to throw an exception in C++?

An exception in C++ is thrown by using the throw keyword from inside the try block. The throw keyword allows the programmer to define custom exceptions. Exception handlers in C++ are declared with the catch keyword, which is placed immediately after the try block.


1 Answers

It doesn't check compile-time, but a conforming compiler should ensure it at run-time.

If a function throws anything outside of its throw-declaration, the C++ run-time should call std::unexpected, if I recall correctly.

like image 130
Kim Gräsman Avatar answered Sep 22 '22 08:09

Kim Gräsman