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-
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.
VS will auto generate the class with the same name for you and also inherit the Exception class.
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 !
- Switch between multiple proxies in Chrome browser [ProxySwitchy Guide] - February 12, 2016
- CISCO VPN CLIENT -REASON 442: FAILED TO ENABLE VIRTUAL ADAPTER [Fix] - January 31, 2016
- CynogenMod 13 (Android Marshmallow [6.0]) on Samsung Galaxy S3 GT-I9300. [21-12-2015] - December 21, 2015