Matthew
Matthew

Reputation: 11603

Throw exception to stop process

Some times in C# I would like to throw an exception that cannot be handled. An escalated exception that results in the process being stopped. Is this possible?

Upvotes: 3

Views: 4869

Answers (6)

Jon Raynor
Jon Raynor

Reputation: 3892

Any exception that is not handled will stop your application. Usually applications have an application or top level exception handler that catches any unhandled exceptions, does any data maintenance and shuts down the application gracefully.

In your case, I think the best approach is to create a new exception that derives from exception class called something like StopApplicationException.

Then whenever you need to stop your application, throw this type of exception. In your catch block further up the call stack:

catch (StopApplicationException)
{
  //Stop your application
}
catch (ArgumentNullException)
{
  //Null Exception Logic goes here...
}
catch  ...And so forth

Upvotes: 0

Roy Dictus
Roy Dictus

Reputation: 33139

It's not really possible because every exception must inherit from the Exception base class, and you can do a catch(Exception).

However, as others have pointed out, you can fail fast. You can also throw exceptions that cannot be caught specifically, like so:

public class MyLibraryClass
{
    private class MyException : Exception { ... }

    public void MyMethod() { throw new MyException(); }
}

Then the caller cannot do a catch(MyException exc), only a catch(Exception exc). But still, that means the exception can be caught.

Upvotes: 0

OJ.
OJ.

Reputation: 29401

That's not an exception, that's an atomic bomb.

Seriously though, there are better ways of handling this scenario. If you're looking to terminate your process look at options like Application.Exit.

Upvotes: 2

Philipp Schmid
Philipp Schmid

Reputation: 5828

How about simply closing the process like this:

Process.GetCurrentProcess().Close();

Upvotes: 2

leppie
leppie

Reputation: 117220

You could do something like:

class BadassException : Exception
{
  public BadassException(string message)
  {
    Environment.FailFast(message);
  }
}

...

throw new BadassException("Erk!!!");

Upvotes: 4

Oded
Oded

Reputation: 498904

If you don't want an exception to be handled, don't handle it.

Upvotes: 2

Related Questions