0
0
C Sharp (C#)programming~5 mins

When clause in catch in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AThrows a new exception
BCatches all exceptions unconditionally
CFilters exceptions based on a condition
DTerminates the program immediately
Which of these is a valid use of when in a catch block?
Acatch (Exception ex) where (ex.Message.Contains("error"))
Bcatch when (ex.Message.Contains("error"))
Ccatch (Exception ex) if (ex.Message.Contains("error"))
Dcatch (Exception ex) when (ex.Message.Contains("error"))
If a when condition is false, what happens?
AThe program crashes
BThe <code>catch</code> block is skipped
CThe exception is ignored
DThe <code>catch</code> block runs anyway
Can you have multiple catch blocks with different when clauses?
AYes, to handle different exception cases
BNo, only one <code>catch</code> block can have a <code>when</code> clause
COnly if they catch the same exception type
DOnly if they are nested
Which C# version introduced the when clause in catch blocks?
AC# 6.0
BC# 5.0
CC# 7.0
DC# 8.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.