throws Exception in method
amehat via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu May 8 05:00:38 PDT 2014
On Thursday, 8 May 2014 at 10:14:27 UTC, Jonathan M Davis via
Digitalmars-d-learn wrote:
> 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
My English might not be very good and I'm not sure I understand.
If I understand what you say, D for all methods (and functions)
can raise exceptions, unless it has nothrow. And if I still
includes exceptions that are thrown are at the time of
compilation.
So I can not write:
public void testMe () throws MyException {}
However, if I write this and my method throws an exception, it
will take place at compile time:
public void testMe () {}
And if do not want an exception thrown, I should write:
public void testMe () : nothrow {}
or perhaps :
public void testMe () pure nothrow @safe {}
Is that correct?
PS: Thanks for the article on the interveiw Anders Hejlsberg, it
enlightens me a little more about how exceptions sen D (and C #;))
More information about the Digitalmars-d-learn
mailing list