Custom Exception in C#
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); } } }
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 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

There are several ways to modify XML formats: manually editing with a text editor such as Notepad; automatically formatting with online or desktop XML formatting tools such as XMLbeautifier; define conversion rules using XML conversion tools such as XSLT; or parse and operate using programming languages such as Python. Be careful when modifying and back up the original files.
