Try/Catch with version condition

Julian julian.fondren at gmail.com
Tue Apr 9 14:56:03 UTC 2019


On Tuesday, 9 April 2019 at 14:43:54 UTC, foo wrote:
> How would I get this to work:
>
> ---
> version(foo) {
>     try {
> }
> throw new Exception("This should only be fatal when the version 
> is not 'foo'.");
> version(foo) {
>     } catch (Exception e) {
>         import std.stdio;
>         writeln(e);
>     }
> }
> ---
>
> The only way I could think of to get this to work would be:
> ---
> version(foo) {
>     try {
>         throw new Exception("This should only be fatal when the 
> version is not 'foo'.");
>     } catch (Exception e) {
>         import std.stdio;
>         writeln(e);
>     }
> } else {
>     throw new Exception("This should only be fatal when the 
> version is not 'foo'.");
> }
> ---
>
> But then that requires too much code duplication.
> What would be the best way to do this?

Something like this maybe?

   import std.stdio;

   void main() {
       try {
           throw new Exception("fatal for non-foo versions");
       } catch (Exception e) {
           version(foo) {
               writeln(e);
           } else {
               throw(e);
           }
       }
       writeln("continuing, probably in version foo");
   }

As used:

   # dmd -version=foo -run version.d
   object.Exception at version.d(6): fatal for non-foo versions
   ----------------
   ??:? _Dmain [0x9de15af]
   continuing, probably in version foo
   # echo $?
   0

vs.

   # dmd -run version.d
   object.Exception at version.d(6): fatal for non-foo versions
   ----------------
   ??:? _Dmain [0xc4fb9a3]
   # echo $?
   1


More information about the Digitalmars-d mailing list