Benutzerdefinierte Ausnahme 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#.
Das obige ist der detaillierte Inhalt vonBenutzerdefinierte Ausnahme in C#. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Heiße KI -Werkzeuge

Undresser.AI Undress
KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover
Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool
Ausziehbilder kostenlos

Clothoff.io
KI-Kleiderentferner

Video Face Swap
Tauschen Sie Gesichter in jedem Video mühelos mit unserem völlig kostenlosen KI-Gesichtstausch-Tool aus!

Heißer Artikel

Heiße Werkzeuge

Notepad++7.3.1
Einfach zu bedienender und kostenloser Code-Editor

SublimeText3 chinesische Version
Chinesische Version, sehr einfach zu bedienen

Senden Sie Studio 13.0.1
Leistungsstarke integrierte PHP-Entwicklungsumgebung

Dreamweaver CS6
Visuelle Webentwicklungstools

SublimeText3 Mac-Version
Codebearbeitungssoftware auf Gottesniveau (SublimeText3)

Heiße Themen











Leitfaden zu Active Directory mit C#. Hier besprechen wir die Einführung und die Funktionsweise von Active Directory in C# sowie die Syntax und das Beispiel.

Leitfaden zum Zufallszahlengenerator in C#. Hier besprechen wir die Funktionsweise des Zufallszahlengenerators, das Konzept von Pseudozufallszahlen und sicheren Zahlen.

Leitfaden zur C#-Datenrasteransicht. Hier diskutieren wir die Beispiele, wie eine Datenrasteransicht aus der SQL-Datenbank oder einer Excel-Datei geladen und exportiert werden kann.

Leitfaden zur Fakultät in C#. Hier diskutieren wir die Einführung in die Fakultät in C# zusammen mit verschiedenen Beispielen und Code-Implementierungen.

Der Unterschied zwischen Multithreading und Asynchron besteht darin, dass Multithreading gleichzeitig mehrere Threads ausführt, während asynchron Operationen ausführt, ohne den aktuellen Thread zu blockieren. Multithreading wird für rechenintensive Aufgaben verwendet, während asynchron für die Benutzerinteraktion verwendet wird. Der Vorteil des Multi-Threading besteht darin, die Rechenleistung zu verbessern, während der Vorteil von Asynchron nicht darin besteht, UI-Threads zu blockieren. Die Auswahl von Multithreading oder Asynchron ist von der Art der Aufgabe abhängt: Berechnungsintensive Aufgaben verwenden Multithreading, Aufgaben, die mit externen Ressourcen interagieren und die UI-Reaktionsfähigkeit asynchron verwenden müssen.

Leitfaden zu Mustern in C#. Hier besprechen wir die Einführung und die drei wichtigsten Arten von Mustern in C# zusammen mit ihren Beispielen und der Code-Implementierung.

Leitfaden zu Primzahlen in C#. Hier besprechen wir die Einführung und Beispiele von Primzahlen in C# sowie die Codeimplementierung.

Es gibt verschiedene Möglichkeiten, XML -Formate zu ändern: manuell mit einem Texteditor wie Notepad bearbeiten; automatisch Formatierung mit Online- oder Desktop -XML -Formatierungswerkzeugen wie XMLBeautifier; Definieren Sie Conversion -Regeln mithilfe von XML -Conversion -Tools wie XSLT; oder analysieren und mit Verwendung von Programmiersprachen wie Python arbeiten. Seien Sie vorsichtig, wenn Sie die Originaldateien ändern und sichern.
