Bird
Raised Fist0

You want to catch exceptions only if their message contains the word "critical" and log them. Which code snippet correctly uses a when clause to do this?

hard🚀 Application Q8 of Q15
C Sharp (C#) - Exception Handling

You want to catch exceptions only if their message contains the word "critical" and log them. Which code snippet correctly uses a when clause to do this?

Acatch (Exception ex) when (ex.Message.Contains("critical")) { Log(ex); }
Bcatch (Exception ex) if (ex.Message.Contains("critical")) { Log(ex); }
Ccatch (Exception ex) { if (ex.Message.Contains("critical")) Log(ex); }
Dcatch (Exception ex) when { ex.Message.Contains("critical"); Log(ex); }
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct when clause usage

    The when clause must have a boolean expression after it to filter exceptions.
  2. Step 2: Check each option

    catch (Exception ex) when (ex.Message.Contains("critical")) { Log(ex); } correctly uses when (ex.Message.Contains("critical")). catch (Exception ex) if (ex.Message.Contains("critical")) { Log(ex); } uses invalid syntax with if. catch (Exception ex) { if (ex.Message.Contains("critical")) Log(ex); } uses if inside catch, not when. catch (Exception ex) when { ex.Message.Contains("critical"); Log(ex); } has invalid when syntax.
  3. Final Answer:

    catch (Exception ex) when (ex.Message.Contains("critical")) { Log(ex); } -> Option A
  4. Quick Check:

    when clause filters exceptions by condition [OK]
Quick Trick: Use when with boolean condition to filter exceptions [OK]
Common Mistakes:
MISTAKES
  • Using if instead of when in catch
  • Putting when block inside catch braces
  • Omitting condition after when

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes