How do I implement a custom exception

In C#, you can implement a custom exception by inheriting from the built-in System.Exception class. This allows you to create exceptions that are specific to your application’s needs. Below is an example of how to create and use a custom exception.

using System; // Define a custom exception public class CustomException : Exception { public CustomException(string message) : base(message) { } } class Program { static void Main(string[] args) { try { throw new CustomException("This is a custom exception message."); } catch (CustomException ex) { Console.WriteLine($"Caught custom exception: {ex.Message}"); } } }

custom exception C# exception handling .NET