Exception programming difficult

Marco Leise Marco.Leise at gmx.de
Mon Aug 13 01:50:47 PDT 2012


Am Mon, 13 Aug 2012 10:00:31 +0200
schrieb "Nathan M. Swan" <nathanmswan at gmail.com>:

> On Sunday, 12 August 2012 at 03:02:50 UTC, Marco Leise wrote:
> > I just got a bit frustrated and wanted to say that I like 
> > working with Exceptions in Java a lot more.
> 
> I don't. When writing a simple command line program, when there's 
> an error, it usually means the user messed up and I can't 
> recover. I just print the message and terminate. I don't want to 
> have to write "throws Exception" for everything.

But now and then you probably write something else than a simple command line program, right?

> The idea sounds nice, but it's annoying in practice. The point of 
> exceptions is to _centralize_ error handling. Being forced to 
> either catch or declare is almost as bad as C-style errno error 
> handling.

Ok, it is annoying. Still exceptions are not just an opaque blob with a stack trace that you catch in your main(). They are more flexible, but it is difficult to efficiently use this flexibility. For example a routine that processes multiple files may continue with the next file on FileNotFoundExceptions, but throw others. A network application may attempt a few times to reconnect in case of a disconnect. That cannot be accomplished by one centralized exception handler. There are also a couple of occasions where a ConvException is better catched and rethrown as a BadServerResponseException (e.g. a number was expected, but something else returned).
In particular when writing a library I want to offer proper exceptions, and since they have the bad nature of aborting all your nested function calls, it is important for me to have the thrown exceptions properly declared - a task that the compiler can do better and faster than me.
As it stands I might diverge from my old practice and use only one exception type for a library.

> Perhaps an annotation might be nice, as long as it doesn't force 
> catching:
> 
> void buggyFunction(string file, int exception) 
> @throws(StdioException);

As someone else said, a D lint tool might help with warnings about undocumented thrown exceptions. But personally I want to be "annoyed" to death by the language until I have made it clear what I want to do with the exceptions, even if I just write "catch (ConvException) { /* cannot happen, input is known good */ }".

I don't know how many there are who think like me. Your @throws proposal for example could be used to tell the compiler that I want Java style checked exceptions for this function and have the compiler check that I listed them all. An empty list would actually be 'nothrow' then.

-- 
Marco



More information about the Digitalmars-d mailing list