Is there a way to throw custom exception without Exception class Is there a way to throw custom exception without Exception class asp.net asp.net

Is there a way to throw custom exception without Exception class


throw new Exception("A custom message for an application specific exception");

Not good enough?

You could also throw a more specific exception if it's relevant. For example,

throw new AuthenticationException("Message here");

or

throw new FileNotFoundException("I couldn't find your file!");

could work.

Note that you should probably not throw new ApplicationException(), per MSDN.

The major draw back of not customizing Exception is that it will be more difficult for callers to catch - they won't know if this was a general exception or one that's specific to your code without doing some funky inspection on the exception.Message property. You could do something as simple as this:

public class MyException : Exception{    MyException(int severity, string message) : base(message)    {        // do whatever you want with severity    }}

to avoid that.

Update: Visual Studio 2015 now offers some automatic implementation of Exception extension classes - if you open the Quick Actions and Refactoring Menu with the cursor on the : Exception, just tell it to "Generate All Constructors".


The Exception class is not an abstract, and like most of the exceptions defined in .NET, takes a string message in one of the constructor overloads - you can therefore use an existing exception type, but with a customized message.

throw new Exception("Something has gone haywire!");throw new ObjectDisposedException("He's Dead, Jim");throw new InvalidCastException(    $"Damnit Jim I'm a {a.GetType().Name}, not a {b.GetType().Name}!");

Because this uses exception types that are known, it makes it easier for thrid parties to extend your libraries as well, since they don't need to look for MyArbitraryException in catch statements.


Short answer - no.

There is a good reason for enforcing the inheritance of custom exceptions; people need to be able to handle them. If you could throw your custom exception without having a type, people wouldn't be able to catch that exception type.

If you don't want to write a custom exception, use an existing exception type.