The Right Approach to Exceptions

Nick Sabalausky a at a.a
Sun Feb 19 10:49:24 PST 2012


"Robert Clipsham" <robert at octarineparrot.com> wrote in message 
news:jhref7$bo$1 at digitalmars.com...
> On 18/02/2012 23:13, Andrei Alexandrescu wrote:
>> On 2/18/12 4:26 PM, Jonathan M Davis wrote (abridged):
>> GetOptException
>> FlagArgumentMissingException
>> InvalidFlagArgumentException
>> UnknownFlagException
>> FileException
>> FileNotFoundException
>> NotFileException
>> NotDirException
>> AccessDeniedException
>>
>> I died inside a little.
>>
>> Andrei
>
> Perhaps something like:
>
> class PhobosException : Exception
> {
>     this(string _module, uint flags) { ... }
> }
>
> try
> {
>     doSomething();
> }
> catch(PhobosException e)
> {
>     // An exception was thrown by phobos
>     if (e.moduleOf == "file") {
>         // An exception was thrown by std.file
>         if (e.flags & FileException.NotFound) {
>             // File wasn't found
>         }
>     } else if (e.moduleOf == "stdio") {
>         // An exception was thrown by std.stdio
>     }
>     // We only want to handle file and stdio exceptions, rethrow
>     throw e;
> }
>
> Some pros/cons:
>  * Catch-all for all phobos exceptions
>  * No binary bloat from having lots of exception classes
>  * Can still handle specific exceptions
>  * e.flags isn't type-safe
>  * It's not particularly pretty
>  * Can only have up to 32 different "exceptions" in a module (64 if you 
> make it a ulong)
>  * It looks stupid if you come from an OOP language like java and you're 
> used to having 5000 catch blocks
>  * No need to decide on any exception hierarchy, just throw a 
> PhobosException
>

No, exceptions need to be based around semantics, not modules. The former is 
reusable and is well-proven to be very useful. The latter isn't particularly 
useful in general. And if anyone does have use for it, we could just add 
"moduleOf" to Exception, no need for it to be phobos-specific.





More information about the Digitalmars-d mailing list