Bird
Raised Fist0
C Sharp (C#)programming~20 mins

When clause in catch in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
When Clause Catch Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of try-catch with when clause filtering
What will be the output of this C# program when the input number is 5?
C Sharp (C#)
using System;
class Program {
    static void Main() {
        int number = 5;
        try {
            if (number < 10) throw new Exception("Small number");
            Console.WriteLine("Number is large");
        }
        catch (Exception ex) when (number > 10) {
            Console.WriteLine("Caught exception for large number");
        }
        catch (Exception ex) when (number < 10) {
            Console.WriteLine("Caught exception for small number");
        }
    }
}
ACaught exception for small number
BCaught exception for large number
CNumber is large
DNo output
Attempts:
2 left
💡 Hint
Look at the when clauses and which one matches the number 5.
Predict Output
intermediate
2:00remaining
Behavior of multiple catch blocks with when clauses
What will this program print when the input number is 15?
C Sharp (C#)
using System;
class Program {
    static void Main() {
        int number = 15;
        try {
            if (number > 10) throw new InvalidOperationException("Too large");
            Console.WriteLine("Number is small");
        }
        catch (InvalidOperationException ex) when (number < 10) {
            Console.WriteLine("Caught invalid operation for small number");
        }
        catch (InvalidOperationException ex) when (number > 10) {
            Console.WriteLine("Caught invalid operation for large number");
        }
    }
}
ACaught invalid operation for small number
BUnhandled exception
CCaught invalid operation for large number
DNumber is small
Attempts:
2 left
💡 Hint
Check which when clause matches the number 15.
Predict Output
advanced
2:00remaining
Effect of when clause on exception filtering
What will be the output of this program?
C Sharp (C#)
using System;
class Program {
    static void Main() {
        int number = 0;
        try {
            number = 10 / 0;
        }
        catch (DivideByZeroException ex) when (number == 0) {
            Console.WriteLine("Divide by zero caught when number is zero");
        }
        catch (DivideByZeroException ex) {
            Console.WriteLine("Divide by zero caught");
        }
    }
}
ADivide by zero caught when number is zero
BDivide by zero caught
CNo output
DUnhandled exception
Attempts:
2 left
💡 Hint
Check the value of number when the exception is thrown and the when clause condition.
Predict Output
advanced
2:00remaining
When clause with multiple conditions
What will this program print?
C Sharp (C#)
using System;
class Program {
    static void Main() {
        int number = 7;
        try {
            if (number % 2 == 1) throw new Exception("Odd number");
        }
        catch (Exception ex) when (number > 5 && number < 10) {
            Console.WriteLine("Caught exception for odd number between 5 and 10");
        }
        catch (Exception ex) {
            Console.WriteLine("Caught exception");
        }
    }
}
ACaught exception
BCaught exception for odd number between 5 and 10
CNo output
DUnhandled exception
Attempts:
2 left
💡 Hint
Check the when clause condition and the value of number.
🧠 Conceptual
expert
2:00remaining
Understanding when clause effect on exception propagation
Consider this code snippet. Which statement is true about the behavior of the when clause in the catch block?
C Sharp (C#)
try {
    throw new Exception("Error");
}
catch (Exception ex) when (false) {
    Console.WriteLine("This will never run");
}
catch (Exception ex) {
    Console.WriteLine("Caught in general catch");
}
AThe first catch block will catch the exception because the when clause is ignored.
BThe exception will not be caught and will crash the program.
CThe program will not compile because when clause cannot be false.
DThe exception will be caught by the second catch block because the when clause in the first catch evaluates to false.
Attempts:
2 left
💡 Hint
Think about how the when clause filters exceptions.

Practice

(1/5)
1.

What does the when clause do in a catch block in C#?

easy
A. It adds a condition to run the catch block only if the condition is true.
B. It defines a new exception type to catch.
C. It skips the catch block entirely.
D. It makes the catch block run before the try block.

Solution

  1. Step 1: Understand the purpose of the when clause

    The when clause adds a condition to a catch block.
  2. Step 2: Effect of the when clause in exception handling

    The catch block runs only if the condition after when is true, otherwise it skips.
  3. Final Answer:

    It adds a condition to run the catch block only if the condition is true. -> Option A
  4. Quick Check:

    when clause = conditional catch [OK]
Hint: when clause filters catch by condition [OK]
Common Mistakes:
  • Thinking when defines a new exception type
  • Assuming catch runs always regardless of when
  • Confusing when with finally block
2.

Which of the following is the correct syntax to use a when clause in a catch block?

try {
    // code
} catch (Exception ex) _____ {
    // handle
}
easy
A. while (ex.Message.Contains("error"))
B. if (ex.Message.Contains("error"))
C. where (ex.Message.Contains("error"))
D. when (ex.Message.Contains("error"))

Solution

  1. Step 1: Recall the correct keyword for condition in catch

    The correct keyword to add a condition in catch is when.
  2. Step 2: Match the syntax with the options

    Only when (ex.Message.Contains("error")) uses when correctly with the condition.
  3. Final Answer:

    when (ex.Message.Contains("error")) -> Option D
  4. Quick Check:

    Use 'when' keyword for catch condition [OK]
Hint: Use 'when' keyword, not if/where/while in catch [OK]
Common Mistakes:
  • Using if instead of when in catch
  • Confusing when with where or while
  • Missing parentheses after when
3.

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");
}
medium
A. Caught general exception
B. Caught invalid operation
C. No output
D. Runtime error

Solution

  1. Step 1: Identify the thrown exception and matching catch

    The code throws InvalidOperationException with message containing "Invalid".
  2. 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.
  3. Final Answer:

    Caught invalid operation -> Option B
  4. Quick Check:

    when condition true runs first catch [OK]
Hint: Check exception type and when condition carefully [OK]
Common Mistakes:
  • Ignoring the when condition and picking second catch
  • Assuming no output if when is used
  • Confusing exception types
4.

Find the error in this code snippet:

try {
    // some code
} catch (Exception ex) when ex.Message == "Error" {
    Console.WriteLine("Error caught");
}
medium
A. catch block must not have a condition
B. Cannot use when with Exception type
C. Missing parentheses around the when condition
D. Console.WriteLine is not allowed in catch

Solution

  1. Step 1: Check syntax of when clause

    The condition after when must be enclosed in parentheses.
  2. Step 2: Identify the missing parentheses in the code

    The code uses when ex.Message == "Error" without parentheses, which is invalid syntax.
  3. Final Answer:

    Missing parentheses around the when condition -> Option C
  4. Quick Check:

    when condition needs parentheses [OK]
Hint: Always put parentheses after when [OK]
Common Mistakes:
  • Omitting parentheses around when condition
  • Thinking when can't be used with Exception
  • Believing catch can't have code inside
5.

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?

hard
A. Parameter error, because the when condition matches the ParamName.
B. Other argument null error, because when clause is ignored.
C. No output, because exception is not caught.
D. Runtime error due to duplicate catch blocks.

Solution

  1. Step 1: Identify the thrown exception and its property

    The code throws ArgumentNullException with ParamName set to "param".
  2. Step 2: Check the when clause condition in the first catch

    The first catch has a when clause checking if ex.ParamName == "param", which is true, so this catch runs.
  3. Step 3: Understand catch block selection

    The second catch is ignored because the first matching catch with true when condition handles the exception.
  4. Final Answer:

    Parameter error, because the when condition matches the ParamName. -> Option A
  5. Quick Check:

    when true catches first matching block [OK]
Hint: when filters catch; first true condition wins [OK]
Common Mistakes:
  • Ignoring when condition and picking second catch
  • Thinking duplicate catch causes error
  • Assuming exception is uncaught