How to declare immutable struct outside of try catch and reference it later

kdevel kdevel at vogtner.de
Sun Dec 3 14:16:42 UTC 2017


On Sunday, 3 December 2017 at 05:49:54 UTC, Fra Mecca wrote:
> I have this code:
>     Configuration conf = void ;
>     try {
>         conf = parse_config("config.sdl");
>     } catch (Exception e) {
>         std.stdio.stderr.writeln("Error reading configuration 
> file: ", e.msg);
>         exit(1);
>     }

Since most programs have more than place where execution must be 
terminated, you end up dupliating that try-catch-code all over 
the program making it unreadable. When you try to avoid calling 
exit this problem will not arise. You can simply write

```
    auto conf = parse_config("config.sdl");
```

The exception unwinds the stack and terminates the program. If a 
stacktrace on the command line does not suffice I would wrap the 
main-code in a try-catch block. Your function parse_config should 
support this coding style by putting a whole sentence into the 
Exception instead of the mere filename, then the try-catch 
wrapper in main may look like this:

```
int main ()
{
    try {
       real_main ();
    }
    catch (Exception e) {
       std.stdio.stderr.writeln(e.msg);
       return 1;
    }
    return 0;
}
```



More information about the Digitalmars-d-learn mailing list