The Right Approach to Exceptions

Jonathan M Davis jmdavisProg at gmx.com
Sat Feb 18 14:34:40 PST 2012


On Saturday, February 18, 2012 15:14:04 Andrei Alexandrescu wrote:
> On 2/18/12 1:27 PM, Alex Rønne Petersen wrote:
> > Point taken. I suggested GetOptException initially because, based on
> > usage patterns of std.getopt, it seems to be most common to just catch
> > the exception (be it a parsing error, type coercion error, or whatever)
> > and print it.
> 
> In fact for the vast majority of exceptions it seems to be most common
> to just catch the exception and print it.
> 
> Tutorial examples never help, either. They go something like:
> 
> try {
>    ... stuff ...
> } catch (DatabaseException e) {
>    print("There was a database exception: ", e);
> } catch (NetworkException e) {
>    print("There was a network exception: ", e);
> }
> 
> etc.

If that's what you're doing, then you can just catch Exception. But if you're 
actually going to _use_ the fact that you have typed Exceptions, then you can 
do error handling specific to what went wrong, and it can be very useful.

It becomes even more important with more complex programs. If I call a 
function, and it throws a FileException, then I know that the operation failed 
to operate on the file properly and can handle it appropriately, whereas if it 
threw a ParserException, then I know that it failed in parsing the file and can 
handle _that_ appropriately. It gets even better when you get more specific 
exceptions such as FileNotFoundException or FileOpenFailedException, because 
then you can handle stuff very specific to what exactly what went wrong.

Exception can't give you any of that. All it tells you is that something went 
wrong, and the best that you can do is print a message like your example does.

I'd hate to see us have a crippled exception hierarchy just because some 
people mishandle exceptions and simply print out messages on failure in all 
cases. Obviously sometimes that's what you have to do, but often you can 
handle them much better, and that's part of the reason that we  have 
_Exception_ and not just Error. And a proper exception hierarchy can be very 
benificial to programmers who actually use it correctly.

- Jonathan M Davis


More information about the Digitalmars-d mailing list