Bird
Raised Fist0

You want to read a number from user input and handle errors if the input is not a number. Which code snippet correctly uses exception handling to do this?

hard🚀 Application Q15 of Q15
C Sharp (C#) - Exception Handling
You want to read a number from user input and handle errors if the input is not a number. Which code snippet correctly uses exception handling to do this?
Atry { int num = int.Parse(Console.ReadLine()); Console.WriteLine($"You entered {num}"); } catch (FormatException) { Console.WriteLine("Please enter a valid number."); }
Bint num = int.Parse(Console.ReadLine()); Console.WriteLine($"You entered {num}");
Ctry { int num = Console.ReadLine(); Console.WriteLine($"You entered {num}"); } catch (Exception) { Console.WriteLine("Error occurred."); }
Dtry { int num = Convert.ToInt32(Console.ReadLine()); } finally { Console.WriteLine("Input processed."); }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    We want to read a number and catch errors if input is not a valid number.
  2. Step 2: Check each option for correct exception handling

    try { int num = int.Parse(Console.ReadLine()); Console.WriteLine($"You entered {num}"); } catch (FormatException) { Console.WriteLine("Please enter a valid number."); } uses try with int.Parse and catches FormatException, which is correct. int num = int.Parse(Console.ReadLine()); Console.WriteLine($"You entered {num}"); has no error handling. try { int num = Console.ReadLine(); Console.WriteLine($"You entered {num}"); } catch (Exception) { Console.WriteLine("Error occurred."); } tries to assign string to int without parsing. try { int num = Convert.ToInt32(Console.ReadLine()); } finally { Console.WriteLine("Input processed."); } uses finally but no catch, so errors are not handled.
  3. Final Answer:

    try { int num = int.Parse(Console.ReadLine()); Console.WriteLine($"You entered {num}"); } catch (FormatException) { Console.WriteLine("Please enter a valid number."); } -> Option A
  4. Quick Check:

    Try-catch with int.Parse and FormatException = A [OK]
Quick Trick: Use try-catch around int.Parse to catch invalid input [OK]
Common Mistakes:
MISTAKES
  • Not using try-catch for parsing input
  • Assigning string directly to int variable
  • Using finally without catch to handle errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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