Exception programming difficult

Marco Leise Marco.Leise at gmx.de
Sat Aug 11 20:02:25 PDT 2012


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---

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.

---D->>

/**
 * Receives a response from the server.
 * 
 * Some explanation of what
 * the function does in detail.
 * 
 * Params:
 *    response = receives the whole response
 * Throws: 
 *    UnexpectedResponseException if the server sent us garbage
 *
 *    UnauthenticatedException we need retry after we have logged in
 *
 *    SecurityException we have to switch to a secure connection for this
 *
 *    DisconnectException the connection was unexpectedly terminated
 * Returns: the associated response code
 */

<<-D---

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.

-- 
Marco



More information about the Digitalmars-d mailing list