Home > Backend Development > C#.Net Tutorial > Custom Exception in C#

Custom Exception in C#

王林
Release: 2024-09-03 15:21:32
Original
1150 people have browsed it

In the application we are working on, when a violation of a business rule occurs, we raise a custom exception to handle the situation. A custom exception is an exception that is specifically created to address unique scenarios in our application. To create a custom exception, we derive a new class from either the ApplicationException or Exception class in C#. The ApplicationException class is included in the .NET Framework starting from version .NET v1.0 and is designed to serve as a base class for custom exception classes in C#.

Working of Custom Exception in C#

  • Exceptions handle the type of errors that happen during the application execution. 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.
  • Classes represent the exceptions in C#. 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.
  • The 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);
}
}
}
Copy after login

Output:

Custom Exception in C#

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();
}
}
}
Copy after login

Output:

Custom Exception in C#

Explanation:

  • In the above program, a namespace called exception handling is defined. Then this class called the odd num exception class, is created by inheriting the exception class. Then the property message is 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 is done by checking if the remainder of the 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#.

The above is the detailed content of Custom Exception in C#. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template