Is there any use for C++ throw decoration?

2020-02-01 03:37发布

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.

标签: c++ exception
4条回答
我想做一个坏孩纸
2楼-- · 2020-02-01 04:01

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
查看更多
啃猪蹄的小仙女
3楼-- · 2020-02-01 04:05

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.

查看更多
贼婆χ
4楼-- · 2020-02-01 04:11

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();
查看更多
仙女界的扛把子
5楼-- · 2020-02-01 04:20

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.

查看更多
登录 后发表回答