Exception programming difficult

SomeDude lovelydear at mailmetrash.com
Wed Aug 15 10:44:13 PDT 2012


On Monday, 13 August 2012 at 08:00:33 UTC, Nathan M. Swan wrote:
> 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.
>
> void main(string[] args) {
>     try {
>         realMain(args);
>         return 0;
>     } catch (Exception e) {
>         stderr.writeln(e.msg);
>     }
> }
>
> 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.
>

Or you could have told him HOW he messed up. By just throwing an 
Exception, you are not helpful at all, you are just telling that 
he is an ass and that he will be punished for that. Or maybe he 
will curse you thinking that your program doesn't work.

Let's say I write a FileParser class  which will read a table of 
doubles in a file. I use a number of methods defined in the JDK 
like say Double.parse(String) which throws a 
NumberFormatException("on line" + lineNumber), and catching that 
exception, I am able to tell the user that one of the numbers on 
line lineNumber is badly formatted, instead of just telling him 
that reading the file with 200,000 lines crashed the program. If 
I catch an IOException as well, I can inform him that the file is 
unreadable instead (but that the formatting was not yet in 
cause). But if I catch a FileNotFoundException first (which 
derives from IOException), I can be more helpful by informing 
him/her that the filename passed to the program is wrong.
These are entirely different classes of errors, so they need to 
be distinguished if they are to be handled differently, which is 
not possible with Exception.

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

It's like saying adding typing to the language is nice as long as 
it's not enforced by the compiler.


More information about the Digitalmars-d mailing list