Skip to main content

How to Throw an Exception in C#

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

Some methods can't return a sensible result for some inputs: the average of no numbers at all, for example. In C#, such a method stops with throw, which hands an exception, with a message saying what went wrong, to whoever called it.

Syntax​

Syntax
throw new <ExceptionType>("<message>");
PartWhat it does
throwStops the method at once and passes the exception to the caller. Nothing after it in the method runs.
new <ExceptionType>(...)Creates the exception, such as InvalidOperationException or ArgumentException.
"<message>"Says what went wrong. Callers can read it from the exception's Message.

Microsoft's exception-handling statements reference: "Use the throw statement to throw an exception." The InvalidOperationException reference: "The exception that is thrown when a method call is invalid for the object's current state."

The Example​

An Average method works out the average of some numbers, and throws when it gets none. The program calls it twice, once with 4 and 6 and once with an empty array, inside a try block that catches the exception.

Prerequisites​

  • The .NET 10 SDK or newer, which runs a single .cs file with dotnet run. This guide uses .NET SDK 10.0.404.

Step 1: Write the Code​

Create a file named main.cs in an empty folder:

main.cs, which prints Average of 4 and 6 and Average of an empty array inside a try block, catches InvalidOperationException and prints its message, where Average throws a new InvalidOperationException with the message Add at least one number. when the array is empty.

main.cs
try
{
Console.WriteLine(Average([4, 6]));
Console.WriteLine(Average([]));
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}

static double Average(int[] numbers)
{
if (numbers.Length == 0)
{
throw new InvalidOperationException("Add at least one number.");
}

return numbers.Average();
}

Average checks its input first and throws before doing any work. The catch block receives the exception as ex and prints its Message.

Step 2: Run It​

Terminal
dotnet run main.cs
Output
5
Error: Add at least one number.

A zsh terminal where dotnet run main.cs prints 5 and Error: Add at least one number.

The average of 4 and 6 is 5. The second call threw, so Average returned nothing; the rest of the try block was skipped, and the catch printed the message. The command is the same in zsh, bash and PowerShell.

What Happens When Nobody Catches It​

Without try and catch, the exception reaches the top of the program:

main.cs
Console.WriteLine(Average([]));

static double Average(int[] numbers)
{
if (numbers.Length == 0)
{
throw new InvalidOperationException("Add at least one number.");
}

return numbers.Average();
}
Output
Unhandled exception. System.InvalidOperationException: Add at least one number.
at Program.<<Main>$>g__Average|0_0(Int32[] numbers) in /Users/you/demo/main.cs:line 7
at Program.<Main>$(String[] args) in /Users/you/demo/main.cs:line 1

The program stopped and printed the exception's type, its message and where it was thrown: line 7, inside Average, called from line 1. Microsoft's exceptions overview: "If no exception handler for a given exception is present, the program stops executing with an error message."

Common Mistakes​

MistakeWhat happensDo this instead
Throwing without a message, as in throw new InvalidOperationException();The caller gets a generic message that doesn't say what to fixSay what went wrong and how to fix it
Catching Exception everywhereUnrelated bugs are swallowed along with the expected failureCatch the specific type you expect
Writing throw ex; to pass on a caught exceptionThe original stack trace is replacedWrite throw; inside the catch block

Troubleshooting​

SymptomLikely causeFix
Unhandled exception. and the program stopsNothing catches the exceptionAdd a try and catch where the program can recover
The catch block never runsIt catches a different exception typeCatch the type that's thrown, or a base type of it

FAQ​

Which exception type should I throw?​

Pick the most specific built-in one that fits. Use ArgumentException, or ArgumentNullException and ArgumentOutOfRangeException, when the caller passed a bad argument. Use InvalidOperationException when the call doesn't make sense in the current state. An empty input sits between the two; the example follows .NET's own LINQ Average(), which throws InvalidOperationException: Sequence contains no elements for an empty array.

How do I pass on an exception I caught?​

Write throw; on its own inside the catch block. The reference: "throw; preserves the original stack trace of the exception, which is stored in the Exception.StackTrace property. In contrast, throw e; updates the StackTrace property of e."

Conclusion​

throw new InvalidOperationException("Add at least one number."); stops the method and hands the problem to its caller, with a message that says what to fix. Catch it where the program can recover, keep throw; for passing it on, and expect the program to stop when nobody catches it.

Additional Resources​