Loading
0x60Lesson 7 of 9

Handle exceptions and validate input

Build resilient programs that can cope with imperfect input.

15 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Catch format errors and keep processing valid records.

Exceptions represent runtime failures such as invalid parsing or missing files. Catch expected exceptions close to where they can be handled. In input-heavy scripts, validating and skipping bad records is often better than failing the whole run.

Program.cs · C# 12
1using System;
2
3class Program
4{
5    static void Main()
6    {
7        string token = Console.ReadLine() ?? "";
8        if (int.TryParse(token, out int value))
9        {
10            Console.WriteLine(value * 2);
11        }
12        else
13        {
14            Console.WriteLine("invalid");
15        }
16    }
17}
Output
Input: 12
24

TryParse avoids exceptions for common parse checks. Use try/catch when the API throws and there is no TryX alternative, or when you need to recover from specific exceptions.

Key takeaways

  • Use TryParse to validate numeric input safely.

  • Handle expected failures explicitly.

  • Favor predictable fallbacks in automation scripts.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write C#

Write C# 12 in the editor and run it against sample input. .NET 8 compiles and runs the code through Wandbox, a free public service; your source and test input are sent there.

Exercise 1

Sum valid integers only

+25 XP

Read an integer n and then n tokens. Sum only the tokens that are valid integers and print the total.

  • Mixed tokens
  • All invalid
main.c
Loading editor…

C# 12 code is compiled and run with .NET 8 on Wandbox, a free public service. Your source code and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…