In C#, exceptions are thrown when something goes wrong during the execution of a program. Throwing exceptions is a way of signaling that an error has occurred, and it can be used to interrupt the normal flow of the program.
Syntax
throw new Exception("Error message here");
Types of Exceptions
C# provides many types of Exceptions
- System.Exception: The base class for all exceptions.
- ArgumentNullException: Thrown when a method receives a null argument that is not allowed.
- ArgumentOutOfRangeException: Thrown when an argument is outside the allowed range.
- InvalidOperationException: Thrown when an operation is not valid due to the current state.
- FileNotFoundException: Thrown when an attempt to access a file that does not exist is made.
Throwing an exception when a method argument is invalid
In this example, we will throw an exception if the parameter provided to a method is invalid (for example, a negative number when a positive one is expected).
using System;
class MyProgram
{
static void Main()
{
try
{
ValidateAge(-21); // Invalid age
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine($"Caught exception: {ex.Message}");
}
}
static void ValidateAge(int age)
{
if (age < 0)
{
throw new ArgumentOutOfRangeException(nameof(age), "Age cannot be negative.");
}
Console.WriteLine("Age is valid.");
}
}
Output:
Caught exception: Age cannot be negative.
Parameter name: age
Parameter name: age
Throwing an exception for a null value (ArgumentNullException)
we throw an ArgumentNullException if the user provides a null value for a required argument.
using System;
class MyProgram
{
static void Main()
{
try
{
DisplayName(null); // Invalid name (null)
}
catch (ArgumentNullException ex)
{
Console.WriteLine($"Caught exception: {ex.Message}");
}
}
static void DisplayName(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name), "Employee Name cannot be null.");
}
Console.WriteLine($"Employee name: {name}");
}
}
Output:
Caught exception: Employee Name cannot be null.
Parameter name: name
Parameter name: name
Throwing a custom exception
We can create own exception classes by inheriting from the Exception base class.
Example:
using System;
class CustomException : Exception
{
public CustomException(string message) : base(message) { }
}
class MyProgram
{
static void Main()
{
try
{
throw new CustomException("This is a custom exception.");
}
catch (CustomException ex)
{
Console.WriteLine($"Caught custom exception: {ex.Message}");
}
}
}
Output:
Caught custom exception: This is a custom exception.