Introduction to Custom Exception in C#
The business rule that applies to the application we are working on gets violated and if an exception be raised for that, such exception is called custom exception and this custom exception class is derived from Application Exception or Exception class and this Application Exception class is included in the .net framework in the version .Net v1.0. and it was designed to make it as a base class of the custom exception class in C# and we make use of the keyword throw to raise a custom exception in C# and these custom exception classes are different from the exceptions created by the system in C#.
Working of Custom Exception in C#
- The type of errors that happen during the application execution are handled by exceptions. By errors, we mean the unexpected problems that arise during the execution of the application. On the contrary, exceptions are expected to take place during the execution of the application for several reasons.
- Exception handling is used by the application to handle the exceptions that are expected to happen during the execution of the application. The handling of exceptions in C# is done using the two keywords try, catch, finally and throw.
- The exceptions in C# are represented by classes. These exception classes in C# are derived from System.Exception class either in a direct manner or in an indirect manner.
- The Application Exception class or the Exception class is used to create custom exceptions that can be thrown.
- Creation of custom exceptions is useful only if these exceptions can be caught and can be handled in a different manner.
- The errors occurred for the application and the logs of the errors can be monitored using an error monitoring tool if we are creating Custom Exception in C#.
Examples
Given below are the examples mentioned:
Example #1
C# program to demonstrate the use of Custom Exception in a program.
Code:
using System;
//a namespace called user defined is defined
namespace UserDefined
{
//a class called test weather is defined
class Testweather
{
//main method is called
static void Main(string[] args)
{
//an instance of the class temperat is defined
Temperat tem = new Temperat();
try
{
//the show method of temperat class is called using the instance of the temperat class
tem.show();
}
catch(WeatheriscoldException e)
{
Console.WriteLine("The weather is cold Exception: {0}", e.Message);
}
Console.ReadKey();
}
}
}
//a custom exception class called Weather is cold Exception class is created which is thrown if the weather is cold
public class WeatheriscoldException: Exception
{
public WeatheriscoldException(string message): base(message)
{
}
}
//a class called temperat is defined
public class Temperat
{
//a variable called temp is defined and assigned to zero
int temp = 0;
//a method called show is defined
public void show()
{
//the temperature is checked to determine the weather
if(temp == 0)
{
throw (new WeatheriscoldException("The temperature is found to be zero and hence the weather is cold"));
}
else
{
Console.WriteLine("The Temperature is: {0}", temp);
}
}
}
Output:
Explanation:
- In the above program, a namespace called user defined is defined. Then a class called test weather is defined. Then the main method is called. Then an instance of the class temperat is defined. Then the show method of temperat class is called using the instance of the temperat class.
- Then a custom exception class called Weather is cold Exception class is created which is thrown if the weather is cold. Then a class called temperat is defined. Then a variable called temp is defined and assigned to zero. Then a method called show is defined. Then the temperature is checked to determine the weather.
Example #2
C# program to demonstrate the use of custom Exception in a program.
Code:
using System;
//a namespace called exception handling is defined
namespace ExceptionHandling
{
//The custom exception class called odd num exception class is created by inheriting the exception class
public class OddNumException : Exception
{
//The property message is being overridden here
public override string Message
{
get
{
return "There cannot be an odd divisor";
}
}
}
//a class called check is defined
class check
{
//main method is called
static void Main(string[] args)
{
//three integer variables are defined
int a, b, c;
Console.WriteLine("Please enter two numbers and type of the numbers must be integer:");
a = int.Parse(Console.ReadLine());
b = int.Parse(Console.ReadLine());
try
{
//checking if the divisor is an odd number or an even number
if (b % 2 > 0)
{
//exception is thrown if the divisor is an odd number
throw new OddNumException();
}
c = a / b;
Console.WriteLine(c);
}
catch (OddNumException two)
{
Console.WriteLine(two.Message);
}
Console.WriteLine("The program ends here");
Console.ReadKey();
}
}
}
Output:
Explanation:
- In the above program, a namespace called exception handling is defined. Then this class called odd num exception class is created by inheriting the exception class. Then the property message is being overridden there. Then a class called check is defined. Then the main method is called. Then three integer variables are defined to take the two input integer variables and the other integer variable is used to store the integer output.
- Then the two integer variables are parsed using parse() method. Then the second integer variable or the divisor is checked to see if it is an odd number or an even number and this done by checking if the remainder of division of divisor by two is more than zero or equal to zero. Then an exception is thrown if the divisor is an odd number.
Advantages
Given below are the advantages mentioned:
- The custom handling of the custom exception types in C# can be done by calling the code.
- The monitoring around the custom exception types can be made custom by using custom exception handling in C#.
Recommended Articles
This is a guide to Custom Exception in C#. Here we discuss working of custom exceptions in C# and examples respectively. You may also have a look at the following articles to learn more –
6 Online Courses | 18 Hands-on Project | 90+ Hours | Verifiable Certificate of Completion
4.6
View Course
Related Courses