Home > Software design >  Exit the program if an exception occurs
Exit the program if an exception occurs

Time:05-05

I'm trying to solve a problem on Hackerrank. It expects me to write the error message "E1" when sth. is given incorrectly.

As you can see below; my result is actually true:

enter image description here

But it does not accept this because of the exception message:

enter image description here

The thing is, that I should exit the program after getting this error. That's why I rethrew the exception in the catch block.

But it leads me to this problem.

    public void InsertEdge(char sth)
    {
        try
        {
            if (sth != sthElse)
                throw new Exception("E1");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            throw;
        }
    } 

Is there a way to exit the program if an exception occurs, without throwing again an unhandled exception?

CodePudding user response:

If your only goal is to terminate the process you could call Environment.Exit(-1).

Take a look here for more details: https://docs.microsoft.com/en-us/dotnet/api/system.environment.exit?view=net-6.0

If you would like to pass an error code with more meaning that '-1' checkout this documentation: https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes

  • Related