On Sat, 18 Feb 2012 13:52:05 -0500, Andrei Alexandrescu <seewebsiteforem...@erdani.org> wrote:

There's a discussion that started in a pull request:

https://github.com/alexrp/phobos/commit/4b87dcf39efeb4ddafe8fe99a0ef9a529c0dcaca

Let's come up with a good doctrine for exception defining and handling in Phobos. From experience I humbly submit that catching by type is most of the time useless.

OK, so after reading about 100 or so of these messages, I stopped. Sorry if this has been said before, but here is my take:

many many times when dealing with exceptions I hate to do this:

class ExceptionTypeA : Exception {...}
class ExceptionTypeB : Exception {...}


try
{
}
catch(ExceptionTypeA ex)
{
   // code
}
catch(ExceptionTypeB ex)
{
   // same f'ing code
}

I know, I could do this:

catch(Exception e)
{
   if(cast(ExceptionTypeA)e || cast(ExceptionTypeB)e)
   {
      // code
   }
   else
     throw e;
}

But that sucks, and as others have pointed out, it kills the stack trace.

So I love the idea that others have specified to have a 'template constraint' type piece for catch. IMO, it should not be a template, but a runtime check. i.e., I don't think we need to templatize the catch, we just need to add extra code to the 'should we catch' check that currently consists of 'does the type match'. This would be a huge improvement over existing exception catching techniques.

So the above would become:

catch(Exception e) if(e is ExceptionTypeA or ExceptionTypeB) // not sure of the exact syntax, maybe the if statement I used above?

I agree the constraints should be pure and nothrow.


On to my second point. One of the issues I have with Java is that exceptions are *overused*. For example, EOF should not be an exception, most files have ends, it's not a very exceptional situation. If there is an intuitive way to use an existing return value to convey an error rather than an exception, I'd prefer the return value. There is a runtime cost just for setting up a try/catch block, even if no exceptions are thrown.

-Steve

Reply via email to