The Right Approach to Exceptions

H. S. Teoh hsteoh at quickfur.ath.cx
Sun Feb 19 14:19:08 PST 2012


On Sun, Feb 19, 2012 at 04:36:29PM -0500, Patrick Down wrote:
[...]
> As a lurker watching this debate with interest I just had an idea out
> of the blue idea that may or may not have value but might reduce the
> desire to create a new exception type Exception type for every error. 
> 
> What if the catch syntax was extended to take both a type and a
> condition.  
> 
> try {
>   write(filename, ...);
> }
> catch(FileException e; e.errno == EEXIST) {
> }
> catch(FileException e; e.errno == EROFS) {
> }
> 
> I realize that this is just syntactic sugar for catch(...) { if(...)
> {}} feel free to shoot it down.
[...]

It's not. This avoids the evil side-effect of resetting the stack trace
when you rethrow an exception you didn't mean to catch inside the catch
block. This is in fact just an alternative syntax for my "catch
signature constraint" idea.

Another side issue, though: IMHO putting errno inside an exception is
not a good thing. It introduces a strong coupling between the caller of
write() and the low-level implementation of write(). This is bad because
should we decide to change the underlying implementation of write(), it
will cause a lot of breakage in all user code that catches
errno-specific exceptions. This breaks encapsulation in an ugly way.

Instead, what we *should* do is to have Phobos define its own *logical*
exception types, rather than implementation-dependent exception types.
For example, conceptually speaking a write operation may fail because of
the target device is full, or the target file already exists. The users
of Phobos *shouldn't* care whether it's errno==EEXIST or it's a
Windows-specific error number that describes this condition. Phobos
needs to encapsulate this in a platform-independent way.

Of course, the implementation-specific info can still be there for
system-dependent code that *wants* to check for system-specific
statuses, for example, to check for a UNIX-specific error that doesn't
exist on Windows, say. But this type of system-specific checking
shouldn't be what Phobos users *generally* depend upon.


T

-- 
He who sacrifices functionality for ease of use, loses both and deserves
neither. -- Slashdotter


More information about the Digitalmars-d mailing list