Exception programming difficult

Timon Gehr timon.gehr at gmx.ch
Sat Aug 11 21:13:45 PDT 2012


On 08/12/2012 05:02 AM, Marco Leise wrote:
> I just got a bit frustrated and wanted to say that I like working with Exceptions in Java a lot more. That has to do first but not foremost with the declaration:
>
> ---Java->>
>
> class MyException extends Exception {
>    public MyException(String msg) {
>      super(msg);
>    }
>    public MyException(String msg, Throwable next) {
>      super(msg, next)
>    }
> }
>
> <<-Java---
> ---D->>
>
> class MyException : Exception {
>    this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null) {
>      super(msg, file, line, next);
>    }
>    this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__) {
>      super(msg, file, line, next);
>    }
> }
>
> <<-D---
>

---D->>
class MyException : Exception {
     mixin GenericExceptionConstructors;
}
<<-D---

> The other think that I'd really like to see is an actual declaration for the user of a function to see what exceptions can be thrown - also inferred and checked by the compiler. In Java you cannot compile a function that throws some (checked) exception and doesn't declare that like this:
>
> ---Java->>
>
> void foo() throws MyException {
>    throw new MyException("test");
> }
>
> <<-Java---
>
> This way you, as the author, are always aware of which Exceptions you handle inside the function and which may escape. This escalates to callers of the function as well, so that in the end the public API has an exact list of possibly thrown exceptions that the user must handle.
> I have around a dozen different exceptions in a hierarchy and a few nested function calls. It's a maintenance horror to keep the DDoc up to date about thrown Exceptions. It also doesn't check the spelling or offers a link to the Exceptions.
>
> ...
>
> I know that the Java way isn't perfect, because some lazy people write dummy exception handlers to silence the errors,
> but its a worse solution to _not_ notify the user of a function, that it potentially throws exceptions, I think. So I
> wish D was explicit about thrown Exceptions.
>

Well, any scheme for explicit exception annotations I can think of
is either unsound or impractical. What would you suggest concretely?


More information about the Digitalmars-d mailing list