try & catch / repeating code - DRY

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed May 23 12:24:54 UTC 2018


On Wednesday, May 23, 2018 04:07:25 Ali Çehreli via Digitalmars-d-learn 
wrote:
> On 05/23/2018 12:47 AM, Robert M. Münch wrote:
> > On 2018-05-22 18:34:34 +0000, Ali ‡ehreli said:
> >> An idiom known in C++ circles is a Lippincott function:
> >>
> >>
> >> https://cppsecrets.blogspot.ca/2013/12/using-lippincott-function-for.ht
> >> ml
> >>
> >> Just wanted to mention that it can be a part of a clean solution.
> >
> > Thanks, and I assume that D has the same property WRT exception
> > re-throwing as C++, right?
>
> I think you have to catch and rethrow explicitly:
>
> import std.stdio;
>
> void main() {
>      try {
>          try {
>              throw new Exception("Yo");
>          } catch (Exception e) {
>              writeln("Rethrowing");
>              throw e;
>          }
>      } catch (Exception e) {
>          writeln(e.msg);
>      }
> }
>
> Rethrowing
> Yo
>
> Keeping in mind that it's possible to catch Throwable as well but it's
> considered less sanitary because it would catch Errors as well, which is
> supposed to mean "unrecoverable error". There are long discussions about
> whether one should do that or not...

The short answer to that would be that you should never do it. The long
answer gets considerably more complicated, and while it _can_ make sense
under certain circumstances when you're very careful, it's a minefield of
potential problems such that no one who who isn't a very advanced D user who
really knows what they're doing should even consider it. Increasingly, I
tend to think that D should not have had Errors or any Throwables other than
exceptions and should have just printed something useful and exited in a way
that created a core dump in any case that's supposed to be non-recoverable.
:|

Either way, I think that we should be clear that doing anything involving
catching anything that isn't an Exception or derived from Exception is
fraught with peril and only for advanced users.

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list