Is there any way in C# (i.e. in .NET) to throw a custom exception but without writing all the code to define your own exception class derived from Exception
?
I am thinking something similar you have for example in Oracle PL/SQL where you can simply write
raise_application_error(-20001, 'An arbitary error message');
at any place.
Without using throws When an exception is cached in a catch block, you can re-throw it using the throw keyword (which is used to throw the exception objects). If you re-throw the exception, just like in the case of throws clause this exception now, will be generated at in the method that calls the current one.
In simple words, we can say that a User-Defined Exception or custom exception is creating your own exception class and throwing that exception using the 'throw' keyword. For example, MyException in the below code extends the Exception class.
You can throw it in your code and catch it in a catch clause. And you can but don't need to specify if your method throws it.
No, it is nor mandatory to extend the exception class to create custom exceptions, you can create them just by extending Throwable class, the super class of all exceptions.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With