Handle exceptions and validate input
Build resilient programs that can cope with imperfect input.
- 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.
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}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.
Sum valid integers only
Read an integer n and then n tokens. Sum only the tokens that are valid integers and print the total.
- Mixed tokens
- All invalid
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…