In C# programming, a custom exception refers to a user-created class that extends the pre-existing System.Exception class. This enables the creation of unique error categories tailored to address specific scenarios within the software. One frequent application of custom exceptions involves validating user inputs.
The design of the placeholder element includes a background styled with a linear gradient from #374151 to #1f2937, a border-radius set to 12 pixels, padding of 40 pixels, a margin of 20 pixels on the top and bottom, and text aligned to the center. In addition, the placeholder icon within this element has a font size of 3rem and a margin-bottom of 10 pixels, while the placeholder text is colored in #9ca3af and has a font size of 1rem.
For example, an InvalidAgeException can be implemented to trigger an exception if a user inputs an age below 18, which might be considered unacceptable in specific business guidelines like registration for age-restricted services.
Custom exceptions play a crucial role in coding by illustrating precise errors within the codebase. They enhance comprehension and facilitate issue resolution through the delivery of explicit and insightful error messages. By enabling distinct error handling approaches, custom exceptions contribute to code refinement and organization, ultimately fostering cleaner and well-structured codebases.
Creating a Custom Exception in C#
In C#, programmers can generate custom exceptions by crafting a new class that inherits from the System.Exception class or one of its child classes. This approach enables the management of application-specific errors in a more organized and purposeful manner.
Syntax:
It has the following syntax:
public class MyCustomException : Exception
{
public MyCustomException()
{
}
public MyCustomException(string message)
: base(message)
{
}
public MyCustomException(string message, Exception innerException)
: base(message, innerException)
{
}
}
In this specific syntax, the MyCustomException class derives from System.Exception and provides three constructors. These constructors allow us to define a personalized error message and potentially include an inner exception if needed.
Handling Custom Exceptions
In C#, developers can manage custom exceptions just like they handle standard exceptions by employing a try-catch block. If a custom exception is triggered within the code, it can be captured within a catch block that specifically addresses the custom exception type. This approach allows programmers to offer more detailed and tailored error management for various scenarios.
Syntax:
It has the following syntax:
try
{
CustomExceptionDemo demo = new CustomExceptionDemo();
demo.DoSomething();
}
catch (CustomException ex)
{
Console.WriteLine($" Custom Exception Caught: {ex.Message} " );
// Handle the exception or log it
}
In this particular structure, we capture the CustomException that might be raised by the DoSomething function. This enables us to manage the precise error situation in a structured manner, like recording the error details or presenting a user-friendly notification.
C# Custom Exception Handling Example
Let's consider a scenario to demonstrate the usage of a custom exception in C#.
Example
using System;
public class InvalidAgeException : Exception
{
// default constructor
public InvalidAgeException() : base("Age is not valid.")
{
}
// Constructor with custom message
public InvalidAgeException(string message) : base(message)
{
}
}
public class TestUserDefinedException
{
static void Validate(int age)
{
if (age < 18)
{
throw new InvalidAgeException("Sorry, Age must be at least 18 years. ");
}
}
public static void Main(string[] args)
{
try
{
Validate(15);
}
catch (InvalidAgeException m)
{
Console.WriteLine("Exception caught: " + m.Message);
}
Console.WriteLine("Program continues... ");
}
}
Output:
Exception caught: Sorry, Age must be at least 18 years.
Program continues...
Explanation:
In this instance, we establish a personalized exception named InvalidAgeException, triggering when the age falls below 18. Should the age be below 18, exceptions are raised conveying the specific message "Apologies, Age must be a minimum of 18 years". Within the main function, the exception is managed through a try-catch block, ensuring uninterrupted execution without any abrupt termination.
Why Use Custom Exception in C#
In C#, custom exceptions can be employed for various scenarios. A few examples include:
- Enhancing
- for developers
In C#, developing a custom exception allows us to specify a descriptive error message that effectively communicates the specific issue.
- Exception Handling
In C#, by defining custom exception types, developers can effectively identify and manage errors based on their specific types. This practice contributes to enhancing the reliability and structure of the code, ultimately leading to improved
- .
In C#, employing centralized error-handling logic with custom exceptions enhances code cleanliness and maintainability.
- Guidance
Creating a custom exception in C# serves as self-explanatory code. This approach aids in comprehending the primary reason for an exception and the specific scenarios in which it should be raised.
Types of Exceptions in C#
In C#, there are primarily two categories of exceptions:
- System Exception
- Application Exception
The styling for the placeholder is defined in the following CSS code block:
.placeholder-diagram { background: linear-gradient(135deg, #374151 0%, #1f2937 100%); border-radius: 12px; padding: 40px; margin: 20px 0; text-align: center; }
.placeholder-diagram .placeholder-icon { font-size: 3rem; margin-bottom: 10px; }
.placeholder-diagram .placeholder-text { color: #9ca3af; font-size: 1rem; }
Here, we will explore these specialized exceptions individually.
System Exception
In C# programming, the base class for all exceptions within the .NET Framework is System.Exception. An exception signifies an undesired or unforeseen occurrence during program execution that disrupts the regular flow. Instances of System Exceptions encompass NullReferenceException, IndexOutOfRangeException, DivideByZeroException, and FileNotFoundException. It is also possible to generate personalized exceptions by deriving from this fundamental class.
C# System-defined Exception Example
Let's consider a basic scenario to illustrate the functionality of a pre-defined exception in C#.
Example
using System;
class Point
{
static void Main()
{
try
{
int num = 10;
int z = 0;
int res = num / z;
Console.WriteLine(res);
}
catch (DivideByZeroException m)
{
Console.WriteLine("System Exception Caught: " + m.Message);
}
}
}
Output:
System Exception Caught: Attempted to divide by zero.
Explanation:
In this illustration, we showcase a system exception scenario in C#. Within the try block, the code endeavors to perform a division operation by zero on an integer variable num, a mathematically invalid operation. Consequently, this action triggers an exception. Upon occurrence of the exception, the program flow swiftly transfers to the catch block. Subsequently, the catch block manages the error by displaying an error message.
System-defined Exception Examples
There are multiple instances of system-defined exceptions in C#. A few of these include:
1) Handling IndexOutOfRangeException in C#
Let's consider an instance to demonstrate an IndexOutOfRangeException in C# by utilizing a try-catch block.
Example
using System;
class C# Tutorial
{
static void Main()
{
int[] num = {10, 20, 30};
try
{
Console.WriteLine(num [3]); //throws IndexOutOfRangeException
}
catch (IndexOutOfRangeException m)
{
Console.WriteLine("Error: This index number is not available in the array. ");
Console.WriteLine("Exception message: " + m.Message);
}
Console.WriteLine("Program continues running after handling the exception. ");
}
}
Output:
ERROR!
Error: This index number is not available in the array.
Exception message: Index was outside the bounds of the array.
Program continues running after handling the exception.
Explanation:
In this instance, we instantiate an array called num containing three numeric values. Subsequently, we attempt to retrieve the fourth element, which is not present. The try-catch block captures the exception and displays the error message without causing a program failure.
2) Handling NullReferenceException in C#
Let's consider a scenario to demonstrate a NullReferenceException in C# by utilizing a try-catch block.
Example
using System;
class C# Tutorial
{
static void Main()
{
string t = null;
try
{
Console.WriteLine(t.ToUpper());
}
catch (NullReferenceException m)
{
Console.WriteLine("Error: You tried to use an object that is null. ");
Console.WriteLine("Exception message: " + m.Message);
}
Console.WriteLine("Program continues running after handling the exception. ");
}
}
Output:
ERROR!
Error: You tried to use an object that is null.
Exception message: Object reference not set to an instance of an object
Program continues running after handling the exception.
Explanation:
In this instance, a string variable named t is initialized with a null value, indicating the absence of any assigned value. When an attempt is made to invoke the ToUpper method on this null variable, a NullReferenceException is generated as methods cannot be applied to null objects. To handle this exception, a try-catch block is employed to capture the error and display an appropriate error message, ensuring the program continues to run without interruption.
Application Exception
In C#, an application exception is a subclass of the System.Exception class. It is employed to signify errors that pertain to the application's specific logic or guidelines, as opposed to errors at the system level.
For instance, setting a condition where an exception is thrown during a division operation if the divisor happens to be an odd number.
C# Application Exception Example
Let's consider an example to demonstrate the handling of exceptions in C#.
Example
using System;
class C# Tutorial : Exception
{
public C# Tutorial(string message) : base(message) { }
}
class tech
{
static void Main()
{
try
{
int n = -5;
if (n < 0)
{
throw new C# Tutorial("Negative values are not allowed. ");
}
Console.WriteLine("Number is: " + n);
}
catch (C# Tutorial m)
{
Console.WriteLine("Application error message: " + m.Message);
}
}
}
Output:
Application error message: Negative values are not allowed.
Explanation:
In this instance, we establish a bespoke C# Tutorial exception that extends the Exception class. Within the main function, if the value of n is negative, it triggers the custom exception. Subsequently, the catch block manages the exception and presents a pertinent error statement.
Conclusion
In summary, a custom exception in C# empowers developers to define personalized error types that are tailored to their application's logic. Utilizing custom exceptions enables developers to craft more transparent and easily maintainable code, facilitating the identification and management of particular error scenarios.
C# Custom Exception FAQs
1) What is a custom exception in C#?
In C#, a personalized exception refers to a custom class created by the user that extends the existing System.Exception class. This enables the customization of error types to address unique scenarios within the software. The primary benefit is the enhancement of error comprehension and resolution through the delivery of precise and informative error notifications.
2) How can we raise a custom exception in C#?
A custom exception is triggered by utilizing the throw keyword along with an instance of the custom exception class.
Throw a new instance of the MyCustomException class with the message "An error occurred".
3) How can we catch a custom exception in C#?
In C#, we have the capability to capture a specialized exception by employing a catch block that defines the custom exception type.
try
{
// throw a CustomException
}
catch (CustomException m)
{
// Handle the custom exception
Console.WriteLine($" Custom error: { m.Message } " );
}
4) Why do we create a custom exception in C#?
In C#, custom exceptions play a crucial role in pinpointing precise errors within the code, enhancing clarity and facilitating efficient troubleshooting. By providing explicit and descriptive messages, custom exceptions simplify the process of identifying and resolving issues. They empower developers to manage various errors through tailored approaches.
5) How can exceptions be handled in C#?
In C#, errors are managed through the try and catch blocks. The potentially problematic code is enclosed within the try block, with the catch block being responsible for dealing with any exceptions that arise.
try
{
// Code that might cause an error
}
catch (Exception m)
{
// Code to handle the error
}