tags:

views:

849

answers:

4

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.

A: 

I dont know if the checker/compiler can do that. Perhaps it's just easier to comment it in the function declaration. Well it aint fool proof but if people see that there can be an exception thrown than most of the people will wrap the function call in try and catch.

//Can throw Exception
GetFoo();
PoweRoy
+7  A: 

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.

Kim Gräsman
That's my understanding too. Why you'd want it to do so I've no idea. I personally find `GetFoo() // throws(std::runtime_error)` much more useful than the uncommented equivalent - just as a hint to consumers of my code.
Dominic Rodger
Correct. The practical problem for compile-time checking is that most existing C++ code has no throw specification.
MSalters
Visual C++ 2008 doesn't support this part of standard.
Kirill V. Lyadvinsky
@Kirill: Interesting, I didn't know that.
Kim Gräsman
+1  A: 

Basically, the exception specifications are only good as empty exception specification. Otherwise I think they're an experiment that failed. See phlipsy's answer why.

sbi
+4  A: 

I would also recommend to look at this essay about the exception specifications. It points out the problems of this C++ feature like:

  • It's a shadow type system
  • The compiler checks thrown exceptions only at runtime
  • The triggered default behavior in the case of a thrown but not specified exception is usually unusable and often misunderstood by the programmers
phlipsy