Hello All,
In this blog I'll explain the Custom exception objects in .Net.
Basically .net framework contains the all kind of exception which are sufficient in most cases. But in some times we can define custom exceptions in your own applications. The custom exception improve the error handling and thus increase the overall code quality.
Creating Custom Exception Objects:-
For creating custom exception class we need to derive the System.Exception class. You can either derive directly from it or use an intermediate exception like SystemException or ApplicationException as base class.
For customizing Exception Handling, the following components are necessary:
A custom exception class which would host the exception thrown from the application.
A friendly Application messages that need to be displayed.
In the below example we declare new custom exception, that accept int parameter in its constructor and pass a message to the base constructor describing the issue.
public class NumericException : Exception
{
public NumericException(int number)
: base("Please enter numeric value from 0-9.")
{
}
}
public void RegisterUser(int number)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(Convert.ToString(number), "^[0-9]*$"))
throw new AgeException(NumericException );
}
In above function we are using the custom exception class(NumericException ).
0 Comment(s)