If it compiles (as it does now on GCC), how is that better than old empty throws() declaration? |
The new, arguably improved, way of exception specifications also made the good old "throw()" work better: compiler can apply move-vs-swap optimizations also on throw(). The important difference is that noexcept allow to
conditionally mark your function as non-throwing. Old C++ (C++03) had a problem that you couldn't correctly specify exception specifications for template functions because you didn't know if (and what) the type T was throwing. Consider this function template:
1 2 3 4
|
template< typename T >
T abs( T const& x, T const& y ) {
return (x*x) + (y*y);
}
| |
Does it throw or not? It depends if T operations (addition, multiplication, copy construction) throw. With noexcept you can say:
1 2 3 4 5 6
|
template< typename T >
T abs( T const& x, T const& y )
noexcept( noexcept(T((x*x) + (y*y))) )
{
return (x*x) + (y*y);
}
| |
You may argue that this syntax is silly, but it has one good point about it: it works. This was never possible in C++ before.
No, from every other language than C++ and Java. Every other language with exceptions took a way of unchecked exceptions. And there is really no problem with that. Unchecked exceptions are perfectly ok, as long as you use them for the purpose exceptions has been created for - for exceptional, rare cases. |
You are probably right that there may not exist anything better than unchecked exceptions, however a couple of things needs to be noted.
1. The fact that no-one yet knows how to implement compile-time checked static exceptions that work doesn't mean that it is impossible, and I guess it is worth trying. This is how programming languages evolve and get better.
2. I think anyone would agree that compile-time-checked exceptions are useful
if we found a way to eliminate problems they cause. So again, it is worth the effort to look for the solution.
C++ is known for experimenting. This experimenting sometimes revolutionizes computer programming (this is the case of STL, or intorducing throw-try-catch syntax for exception handling into the mainstream) and sometimes ends in failure (like exported templates, dynamic exception specifications) but in the end it look like the best approach to make progress in the long run.
Regards,
&rzej