throws Exception in method

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu May 8 03:14:06 PDT 2014


On Thu, 08 May 2014 09:15:13 +0000
amehat via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com>
wrote:

> Hello everyone,
>
> in java, you can have exceptions on methods.
> Thus we can write:
> public static void control (String string) throws
> MyException {}
>
> Is that possible in D and if so how does it work? If I write this
> D:
>
> public void testMe () throws MyException {}
>
> The compiler refuses to compile.
>
> What is the proper behavior for this D?
>
> thank you

At this point, the programming community at large seems to have decided that
while checked exceptions seem like a good idea, they're ultimately a bad one.
This article has a good explanation from one of the creators of C# as to why:

http://www.artima.com/intv/handcuffs.html

At this point, Java is the only language I'm aware of which has checked
exceptions (though there may be a few others somewhere), and newer languages
have learned from Java's mistake and chosen not to have them.

What D has instead is the attribute nothrow. Any function marked with nothrow
cannot throw an exception. e.g.

auto func(int bar) nothrow {...}

It's similar to C++11's noexcept except that it's checked at compile time
(like Java's checked exceptions), whereas noexcept introduces a runtime check.

If a function is not marked with nothrow, then the only ways to know what it
can throw are to read the documentation (which may or may not say) or to read
the code. There are obviously downsides to that in comparison to checked
exceptions, but the consensus at this point is that it's ultimately better.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list