In C#, a custom exception is a user-defined exception that extends the built-in Exception class or any of its derived classes. Creating custom exceptions allows you to handle specific error cases in your application in a more meaningful and organized way.
Here's a simple example of creating a custom exception in C#:
using System;
public class CustomException : Exception
{
public CustomException() : base("This is a custom exception.")
{
}
public CustomException(string message) : base(message)
{
}
public CustomException(string message, Exception innerException) : base(message, innerException)
{
}
}
public class Program
{
public static void Main(string[] args)
{
try
{
throw new CustomException("An error occurred due to a custom exception.");
}
catch (CustomException ex)
{
Console.WriteLine("CustomException caught: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("An unexpected error occurred: " + ex.Message);
}
}
}
In this example:
- We define a custom exception class CustomException that inherits from Exception.
- We provide three constructors to allow for different ways to initialize the custom exception.
- In the Main method, we throw an instance of CustomException.
- We catch this custom exception type and print the error message.
Custom exceptions allow you to create specialized exception types that convey specific information about errors or exceptional conditions in your application, making it easier to handle and respond to those scenarios appropriately.
No comments:
Post a Comment