Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to catch an exception.
C Sharp (C#)
try { int result = 10 / [1]; } catch (DivideByZeroException) { Console.WriteLine("Cannot divide by zero."); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-zero number does not cause an exception.
✗ Incorrect
Dividing by zero causes an exception. Catching it prevents the program from crashing.
2fill in blank
mediumComplete the code to throw an exception when input is invalid.
C Sharp (C#)
if (age < 0) { throw new [1]("Age cannot be negative."); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using exceptions unrelated to argument errors.
✗ Incorrect
ArgumentException is used when an argument is invalid, like a negative age.
3fill in blank
hardFix the error in the catch block to handle any exception.
C Sharp (C#)
try { int[] numbers = new int[3]; int x = numbers[5]; } catch ([1]) { Console.WriteLine("An error occurred."); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Catching only specific exceptions misses others.
✗ Incorrect
Catching Exception handles all exceptions, including unexpected ones.
4fill in blank
hardFill both blanks to handle a file error and display a message.
C Sharp (C#)
try { var text = System.IO.File.ReadAllText([1]); } catch ([2]) { Console.WriteLine("File not found."); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong exception type or missing quotes around filename.
✗ Incorrect
Reading "data.txt" may cause FileNotFoundException if the file is missing.
5fill in blank
hardFill all three blanks to catch an exception and print its message.
C Sharp (C#)
try { int num = int.Parse([1]); } catch ([2] ex) { Console.WriteLine([3]); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Parsing a valid number does not cause exception.
✗ Incorrect
Parsing "abc" causes FormatException. Printing ex.Message shows the error.