Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to throw custom exception without Exception class

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.

like image 981
Wernfried Domscheit Avatar asked May 01 '15 20:05

Wernfried Domscheit


People also ask

How can I catch exception without throwing exception?

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.

Can we Throws custom exception?

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.

Can we throw custom exception in catch block?

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.

Can I create custom exception by extending throwable class?

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.


1 Answers

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".

like image 164
Dan Field Avatar answered Sep 16 '22 20:09

Dan Field