nothrow by default
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Sat Jan 11 14:38:50 UTC 2020
On Saturday, January 11, 2020 1:02:09 AM MST Jesse Phillips via Digitalmars-
> On Friday, 10 January 2020 at 22:27:35 UTC, Ola Fosheim Grostad
> > On Friday, 10 January 2020 at 22:00:08 UTC, Jesse Phillips
> > wrote:
> >> My point is c++ is not removing what is being proposed for
> >> adding 'throw'
> > What do you mean? C++ has "throw" as the default. Noexcept is
> > the outlier, so yes, they did remove it.
> Throw was always the default, just like D.
Yes. What C++ had was a runtime attempt at what Java does. You would
optionally specify which exceptions could be thrown from a function (whereas
in Java, it's mandatory to specify). So, if you had
int foo(std::string bar);
then the function could throw anything (even stuff like int, since C++
didn't restrict exception types at all), whereas if you had
int foo(std::string bar) throw(MyExceptionType);
then the function could only throw the type MyExceptionType. This is similar
to Java, but whereas Java statically restricts what can be thrown, C++ did
it at runtime. So, there were _zero_ compile-time checks that no other types
were thrown, and if something else were thrown, it would basically kill your
program. This was a terrible, terrible idea, which is why they started
phasing it out with C++11.
The one aspect of it which was arguably a good idea was throw() - e.g.
int foo(std::string bar) throw();
which was their version of nothrow. It was still a runtime check, but there
are cases where you absolutely can't have an exception be thrown
(destructors being the primary use case), so while it's still bad that it's
a runtime check, it's deemed better to kill the program in such a case than
to continue. So, C++11 introduced noexcept to replace it. e.g.
int foo(std::string bar) noexcept;
noexcept does the same thing as throw(), but throw() is going away along
with throw(MyExceptionType). So, with throw(...) removed, C++ ends up with a
solution similar to what we currently have in D except that noexcept is a
runtime check, whereas nothrow is a compile-time check, and D lets
non-Exception Throwables be thrown anyway, which can get a bit weird.
If we were to add throw as a function attribute and make nothrow the
default, that would be the opposite of what C++ has, just like it's the
opposite of what we currently have in D.
- Jonathan M Davis
More information about the Digitalmars-d