What is the best way to stop App after exception?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Feb 15 08:46:18 PST 2016


On Monday, February 15, 2016 11:38:05 Suliman via Digitalmars-d-learn wrote:
> I have got class Config with method parseconfig. I need terminate
> App if parsing of config was failed. The problem that I do not
> know how to do it better.
>
> void parseconfig()
> {
>   try
>   {
>    //something go wrong
>   }
>
> catch(Exception e)
>   {
>    writeln(e.msg);
>    // throw any exception here
>   }
> }
>
>
> But my main.d also have try catch block and parseconfig() calls
> inside it. The problem that wen exception rise I do not know how
> to terminate app. Exception simply print on screen and app is
> continue.
>
> void main()
>   {
>   try
>    {
>     parseconfig(); // exception was already handled inside:  void
> parseconfig()
>    }
>   }
>
> What is the best practice to stop app?

If you want your app to exit cleanly, it must exit via main. If an Exception
or Error is thrown from main (or bubbles up passed main), then the runtime
will catch it and print it out before exiting the program with a non-zero
exit value. If you don't want your program to exit via exception, then you
need to catch it in main, and if you've caught it in main, then you can just
exit main normally - either by reaching the end of its body or by returning.

But if you're handling the exception inside of another function and not
letting it bubble up to main or throwing another exception for main to
catch, then you're going to have to figure out how to have your functions
return until they get back to main - either that or have the exception reach
main.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list