try & catch / repeating code - DRY

Jacob Carlborg doob at me.com
Tue May 22 18:33:06 UTC 2018


On 2018-05-22 20:20, Robert M. Münch wrote:
> I see that I'm writing
> 
> try {
> ... different code ...
> } catch (myException e) {
>      ... same handling code ...
> }
> 
> over and over again.
> 
> Of course I can put the exception handling code into a function to not 
> duplicate it. However, I still need to write this construct over and 
> over again. Is there a way to handle it more generic? Like:
> 
> ??? (... code ...);
> 
> or
> 
> ??? { ... code ...};
> 
> Where ??? would do the try and re-use the exception handling code 
> everytime? I hope this is understandable.
> 

You can always create a function that takes a delegate or lambda and 
handles the exception in the function. Here are three versions of the 
same thing, depending on how you want the call site to look like.

void handleException1(alias dg)()
{
     try dg();
     catch (Exception e) { /* handle exception */ }
}

void handleException2(lazy void dg)
{
     try dg();
     catch (Exception e) { /* handle exception */ }
}

void handleException3(scope void delegate () dg)
{
     try dg();
     catch (Exception e) { /* handle exception */ }
}

void main()
{
     handleException1!({
         writeln("asd");
     });

     handleException1!(() => writeln("asd"));

     handleException2(writeln("asd"));

     handleException3({
         writeln("asd");
     });
}

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list