C# Custom Exceptions

Custom Exceptions: You can create custom exceptions by creating a new class that derives from the System.Exception class

public class MyCustomException : Exception
{
	public MyCustomException()
	{
	}
	public MyCustomException(string message): base(message)
	{
	}
}

In this example, MyCustomException is a class that derives from the Exception class. It has three constructors that take different parameters:

  • The first constructor takes no arguments and can be used to create an instance of the exception with a default message.
  • The second constructor takes a string argument that represents the error message for the exception.

Throw keyword:

  • To throw a custom exception, you can simply create an instance of your custom exception class and throw it using the throw keyword:
    • throw new MyCustomException(“Something went wrong.”);

You can catch this exception using a try-catch block and handle it accordingly:

try
{
	// Some code that may throw MyCustomException
}
catch (MyCustomException ex)
{
	// Handle the exception
}
Scroll to Top