Creating and Throwing Exceptions

Learn to create custom exception types and use them inside programs.

Custom exception types

Although there are many built-in exception types in .NET, we might need to create our own based on our application requirements.

Note: The only thing we need to create a custom exception type is a class that inherits from Exception.

Imagine we’re building an application with a login feature. We need to check if the user provides the correct username and password. In the case that their credentials are invalid, we need to generate an exception that informs the user that they’ve provided invalid credentials.

We have a method that logs a user in:

public void LogIn(string username, string password)
{
}

We also have to define a custom exception that’s thrown in the case that their credentials are invalid:

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

Our custom exception class does nothing specific. It inherits everything from Exception and uses its constructor to set the Message property. Instead of inheriting from the base Exception class, we could inherit from a class that would be more appropriate in this context. Invalid credentials are essentially invalid arguments. Therefore, we can inherit from the ArgumentException class:

public class InvalidCredentialsException : ArgumentException
{
	public InvalidCredentialsException(string message)
		: base(message)
	{
	}
}

Now, our class has all members of ArgumentException.

Custom exception classes, like any other type, can define their own properties and methods. For our InvalidCredentialsException class, we can create two properties that hold the username and password that caused the exception to be generated:

public class InvalidCredentialsException : ArgumentException
{
	public string Username { get; private set; }
	public string Password { get; private set; }

	public InvalidCredentialsException(string message, string username, string password)
		: base(message)
	{
		Username = username;
		Password = password;
	}
}

Get hands-on with 1400+ tech skills courses.