When clause in catch in C Sharp (C#) - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
We want to understand how using a when clause in a catch block affects the time it takes for a program to handle errors.
Specifically, we ask: does adding a when condition change how long the program runs as input grows?
Analyze the time complexity of the following code snippet.
try
{
for (int i = 0; i < n; i++)
{
ProcessItem(i);
}
}
catch (Exception ex) when (ex.Message.Contains("specific"))
{
HandleSpecificError();
}
catch (Exception ex)
{
HandleGeneralError();
}
This code processes n items in a loop and uses a when clause to catch exceptions with a specific message.
- Primary operation: The
forloop that runsProcessItem(i)ntimes. - How many times: Exactly
ntimes, once for each item. - Exception check: The
whenclause runs only if an exception occurs, checking the message condition.
As n grows, the loop runs more times, so the main work grows with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 calls to ProcessItem |
| 100 | About 100 calls to ProcessItem |
| 1000 | About 1000 calls to ProcessItem |
Pattern observation: The main work grows directly with n. The when clause only runs if an exception happens, so it does not add repeated cost for normal runs.
Time Complexity: O(n)
This means the program's running time grows in a straight line with the number of items processed, regardless of the when clause.
[X] Wrong: "Adding a when clause makes the whole loop slower because it checks the condition every time."
[OK] Correct: The when clause only runs when an exception is thrown, which is usually rare. It does not slow down the normal loop iterations.
Understanding how exception handling affects performance shows you can write clear and efficient error management. This skill helps you build reliable programs that handle problems without slowing down normal work.
What if the when clause checked a complex condition that runs every loop iteration instead of only on exceptions? How would the time complexity change?
Practice
What does the when clause do in a catch block in C#?
Solution
Step 1: Understand the purpose of the when clause
Thewhenclause adds a condition to acatchblock.Step 2: Effect of the when clause in exception handling
The catch block runs only if the condition afterwhenis true, otherwise it skips.Final Answer:
It adds a condition to run the catch block only if the condition is true. -> Option AQuick Check:
when clause = conditional catch [OK]
- Thinking when defines a new exception type
- Assuming catch runs always regardless of when
- Confusing when with finally block
Which of the following is the correct syntax to use a when clause in a catch block?
try {
// code
} catch (Exception ex) _____ {
// handle
}Solution
Step 1: Recall the correct keyword for condition in catch
The correct keyword to add a condition in catch iswhen.Step 2: Match the syntax with the options
Only when (ex.Message.Contains("error")) useswhencorrectly with the condition.Final Answer:
when (ex.Message.Contains("error")) -> Option DQuick Check:
Use 'when' keyword for catch condition [OK]
- Using if instead of when in catch
- Confusing when with where or while
- Missing parentheses after when
What will be the output of this code?
try {
throw new InvalidOperationException("Invalid operation");
} catch (InvalidOperationException ex) when (ex.Message.Contains("Invalid")) {
Console.WriteLine("Caught invalid operation");
} catch (Exception) {
Console.WriteLine("Caught general exception");
}Solution
Step 1: Identify the thrown exception and matching catch
The code throwsInvalidOperationExceptionwith message containing "Invalid".Step 2: Check the when condition in the first catch
The first catch has a when clause checking if message contains "Invalid" which is true, so it runs.Final Answer:
Caught invalid operation -> Option BQuick Check:
when condition true runs first catch [OK]
- Ignoring the when condition and picking second catch
- Assuming no output if when is used
- Confusing exception types
Find the error in this code snippet:
try {
// some code
} catch (Exception ex) when ex.Message == "Error" {
Console.WriteLine("Error caught");
}Solution
Step 1: Check syntax of when clause
The condition afterwhenmust be enclosed in parentheses.Step 2: Identify the missing parentheses in the code
The code useswhen ex.Message == "Error"without parentheses, which is invalid syntax.Final Answer:
Missing parentheses around the when condition -> Option CQuick Check:
when condition needs parentheses [OK]
- Omitting parentheses around when condition
- Thinking when can't be used with Exception
- Believing catch can't have code inside
Consider this code:
try {
throw new ArgumentNullException("param");
} catch (ArgumentNullException ex) when (ex.ParamName == "param") {
Console.WriteLine("Parameter error");
} catch (ArgumentNullException ex) {
Console.WriteLine("Other argument null error");
}What will be printed and why?
Solution
Step 1: Identify the thrown exception and its property
The code throwsArgumentNullExceptionwithParamNameset to "param".Step 2: Check the when clause condition in the first catch
The first catch has a when clause checking ifex.ParamName == "param", which is true, so this catch runs.Step 3: Understand catch block selection
The second catch is ignored because the first matching catch with true when condition handles the exception.Final Answer:
Parameter error, because the when condition matches the ParamName. -> Option AQuick Check:
when true catches first matching block [OK]
- Ignoring when condition and picking second catch
- Thinking duplicate catch causes error
- Assuming exception is uncaught
