Creating Custom Exceptions in .NET using VS 2013 !

Though .NET provides most of the Exception types sufficient for code bases, sometimes there can be a requirement to throw a custom exception in the application.

.NET lets us create custom exceptions for representing errors in the applications. We can create a custom exception to represent some type of error within the application—to give a new, distinct meaning to one or more problems that can occur within the code.


Creating a custom exceptions is fairly easy in VS 2013 and later-

Firstly, throw new CustomException from your method-

CS

 

 

 

 

 

VS will show an error on the CustomException as it cannot find a class with that name.

Now, press Ctrl+. over that class. It will show two options. Select the first option to create the stub for that class.

select

 

 

 

 

 

 

VS will auto generate the class with the same name for you and also inherit the Exception class.

generated

 

 

 

 

 

Now add the following default and parameterized constructors in the class.

class CustomException : Exception
 {
    public CustomException()
    {
    }
    public CustomException(string message)
           : base(message) {} 
    public CustomException(string message, Exception innerException)
          : base(message, innerException) {}
    public CustomException(string format, params object[] args)
          : base(string.Format(format, args)) { }
    public CustomException(string message, Exception innerException)
          : base(message, innerException) { }
    public CustomException(string format, Exception innerException, params object[] args)
          : base(string.Format(format, args), innerException) { }
 }

You can throw the new CustomException with following options-

1. Throw exception with out message

throw new CustomException()

2. Throw exception with simple message

throw new CustomException(message)

3. Throw exception with message format and parameters

throw new CustomException("Exception with parameter '{0}'", param)

4. Throw exception with message and inner exception

throw new CustomException(message, innerException)

5. Throw exception with message format and inner exception.

throw new CustomException("Exception with parameter value '{0}'", innerException, param)

Please leave your comments and feedback.

Thanks for checking out !

Categories
Comments
All comments.
Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.