Recall & Review
beginner
What is the purpose of the
when clause in a catch block in C#?The
when clause allows you to specify a condition that must be true for the catch block to handle the exception. It helps filter exceptions based on custom logic.Click to reveal answer
beginner
How does the
when clause improve exception handling?It lets you catch exceptions only if certain conditions are met, making your error handling more precise and avoiding catching exceptions you don't want to handle there.
Click to reveal answer
beginner
Show a simple example of a
catch block using a when clause.Example:<br>
try {
// code that may throw
} catch (Exception ex) when (ex.Message.Contains("timeout")) {
// handle timeout exceptions only
}Click to reveal answer
intermediate
Can multiple
catch blocks use when clauses in the same try statement?Yes, you can have multiple
catch blocks with different when conditions to handle different cases of exceptions separately.Click to reveal answer
intermediate
What happens if the
when condition evaluates to false in a catch block?If the
when condition is false, the catch block is skipped, and the runtime looks for another matching catch block or rethrows the exception if none match.Click to reveal answer
What does the
when clause in a catch block do?✗ Incorrect
The
when clause filters exceptions so the catch block only runs if the condition is true.Which of these is a valid use of
when in a catch block?✗ Incorrect
The correct syntax uses
when after the exception variable declaration.If a
when condition is false, what happens?✗ Incorrect
If the
when condition is false, the catch block is skipped and the runtime looks for another handler.Can you have multiple
catch blocks with different when clauses?✗ Incorrect
Multiple
catch blocks can use different when clauses to handle different conditions.Which C# version introduced the
when clause in catch blocks?✗ Incorrect
The
when clause in catch blocks was introduced in C# 6.0.Explain how the
when clause works in a catch block and why it is useful.Think about how you might want to catch only specific cases of an error.
You got /3 concepts.
Write a simple C# code snippet using a
catch block with a when clause to handle exceptions with a specific message.Use <code>ex.Message.Contains("text")</code> inside the <code>when</code> clause.
You got /3 concepts.