Skip to main content

How to Catch an Exception Only When a Condition Is True with when in C#

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

catch (FormatException) when (answer.Length == 0) catches a FormatException only when the condition in parentheses is true. When it's false, the exception goes on to the next catch clause, as if this one weren't there.

The C# reference for the when keyword: Use the when keyword in a catch clause to specify a condition that must be true for the handler for a specific exception to execute. The condition is an expression that evaluates to a Boolean value. If it returns true, the exception handler executes; if false, it doesn't.

That lets you handle one exception type in more than one way. The reference on exception-handling statements: You can provide several catch clauses for the same exception type if they distinguish by exception filters.

Syntax​

Syntax
try
{
<code that can throw>
}
catch (<ExceptionType> <e>) when (<condition>)
{
<code that handles the exception>
}
PartWhat it is
<ExceptionType>The type of exception the clause is for, such as FormatException
<e>Optional: a name for the exception object, which <condition> and the block can use
when (<condition>)The filter: a true or false expression, in parentheses. The block runs only when it's true
<code that handles the exception>Runs when the exception has the right type and the condition is true

The Example​

A console app called CatchWhen reads three answers to the question "How old are you?": 42, an empty answer and forty. int.Parse throws a FormatException for the empty answer and for forty, and a filter tells the two apart.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n CatchWhen
cd CatchWhen
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/CatchWhen/CatchWhen.csproj:
Determining projects to restore...
Restored /Users/you/source/CatchWhen/CatchWhen.csproj (in 44 ms).
Restore succeeded.

dotnet new console -n CatchWhen creates a folder named CatchWhen with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or CatchWhen.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the answers and the try block:

Program.cs (the answers and the try block)
// Answers typed into a form that asks for an age.
string[] answers = ["42", "", "forty"];

foreach (string answer in answers)
{
try
{
int age = int.Parse(answer);
Console.WriteLine($"'{answer}': age {age}");
}

int.Parse(answer) turns the text into an int, and throws when the text isn't a whole number. The code that can throw goes in the try block.

Then the clause with the filter:

Program.cs (the clause with a filter)
// Runs only when the condition after when is true: nothing was typed.
catch (FormatException) when (answer.Length == 0)
{
Console.WriteLine($"'{answer}': nothing was typed");
}

when (answer.Length == 0) is the filter. The .NET guide to filters gives the order of the checks: The runtime tests the specific exception first. If the specific exception succeeds, the runtime executes the user filter. So this block runs for a FormatException, and only when the answer is empty.

Last, the clause without a filter:

Program.cs (the clause without a filter)
// For "forty" the condition above is false, so this clause catches the exception.
catch (FormatException)
{
Console.WriteLine($"'{answer}': not a whole number");
}
}

For forty the filter above is false, so the search goes on and this clause catches the exception. The reference sets its place: One of those clauses might have no exception filter. If such a clause exists, it must be the last of the clauses that specify that exception type.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
'42': age 42
'': nothing was typed
'forty': not a whole number

macOS-style terminal window titled Terminal — CatchWhen showing dotnet run printing '42': age 42, then '': nothing was typed, then 'forty': not a whole number

42 became an age. The empty answer and forty both threw a FormatException, but only the empty one made the filter true, so it printed nothing was typed. For forty the filter was false, and the second clause printed not a whole number.

The Complete File​

macOS-style code window titled Program.cs — CatchWhen showing an array of three answers, a foreach with a try block that parses each answer with int.Parse, a catch clause for FormatException with the filter when answer.Length == 0, and a second catch clause for FormatException without a filter

Program.cs
// Answers typed into a form that asks for an age.
string[] answers = ["42", "", "forty"];

foreach (string answer in answers)
{
try
{
int age = int.Parse(answer);
Console.WriteLine($"'{answer}': age {age}");
}
// Runs only when the condition after when is true: nothing was typed.
catch (FormatException) when (answer.Length == 0)
{
Console.WriteLine($"'{answer}': nothing was typed");
}
// For "forty" the condition above is false, so this clause catches the exception.
catch (FormatException)
{
Console.WriteLine($"'{answer}': not a whole number");
}
}

Common Mistakes​

MistakeWhat happensDo this instead
Putting the clause without a filter firstcatch (FormatException) above catch (FormatException) when (answer.Length == 0) didn't build: error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('FormatException')Put the clause with the filter first and the one without a filter last, as the example does
Leaving out the parenthesescatch (FormatException) when answer.Length == 0 didn't build: error CS1003: Syntax error, '(' expected and error CS1026: ) expectedPut the condition in parentheses: when (answer.Length == 0)
A filter that can throwFor an empty answer, answer[0] on its own threw IndexOutOfRangeException. Inside when (answer[0] == 'f') nothing stopped the program: the next clause printed Second clause ran: the filter counted as false. The .NET guide: If an exception occurs during execution of the user-filtered expression, that exception is discarded and the filter expression is considered to have evaluated to false.Write a condition that can't throw. With when (answer.StartsWith('f')), the empty answer printed '': second clause and forty printed 'forty': starts with f

FAQ​

Why not use an if inside the catch block?​

Because a catch block that runs has already caught the exception. To pass it on, you write throw;, and the exception then leaves the whole try statement: the other catch clauses of the same try don't get it. A false filter means the clause never caught it, so the next clause still can. Both versions below parse forty, with a catch (Exception) clause after the FormatException clause and a second try around everything. The version with an if:

Program.cs (an if inside the catch block)
catch (FormatException)
{
if (answer.Length != 0)
{
throw;
}
Console.WriteLine("nothing was typed");
}
Output
The outer try caught FormatException

With catch (FormatException) when (answer.Length == 0) in its place, the same program printed:

Output
The next catch clause of the same try ran

The reference names one more difference: the original call stack and all local variables remain intact during filter evaluation, which helps when you debug.

Can a filter look at an exception without catching it?​

Yes, with a filter that always returns false. The C# guide: An exception filter that always returns false can be used to examine all exceptions but not process them. A typical use is to log exceptions. Here catch (Exception e) when (Log(e)) calls this method for every exception:

Program.cs (a filter that logs)
static bool Log(Exception e)
{
Console.WriteLine($"Logged: {e.GetType().Name}: {e.Message}");
return false;
}
Output
Logged: FormatException: The input string 'forty' was not in a correct format.
The outer try caught the FormatException

The filter logged the exception and returned false, so its block never ran, and the try around it caught the FormatException.

Conclusion​

catch (ExceptionType e) when (condition) handles an exception only when the condition is true. When it's false, the next catch clause gets the exception, so you can handle one exception type in several ways, with the clause without a filter last. Keep the condition simple, because a condition that throws counts as false.

Additional Resources​