Going Further Lesson 14 of 15
C# Exceptions and File Handling
Handle errors with try, catch, finally and throw, know common exceptions, and read and write text files with File.WriteAllLines, File.ReadAllLines and File.AppendAllText.
Programs meet problems: bad input, missing files, division by zero. C# signals these with exceptions. Handling them keeps your program running and gives users helpful messages. This lesson also shows how to save data to files.
try and catch
string[] inputs = { "120", "abc", "0" };
foreach (string input in inputs)
{
try
{
int people = int.Parse(input);
int share = 600 / people;
Console.WriteLine($"{input} people: {share} each");
}
catch (FormatException)
{
Console.WriteLine($"{input}: not a number");
}
catch (DivideByZeroException)
{
Console.WriteLine($"{input}: can't divide by zero");
}
}
Output
120 people: 5 each abc: not a number 0: can't divide by zero
When an exception happens inside try, C# jumps to the first matching catch block and then continues after the whole try/catch.
Common exceptions
| Exception | Typical cause |
|---|---|
FormatException | int.Parse("abc") |
DivideByZeroException | Integer division by zero |
IndexOutOfRangeException | arr[10] in a smaller array |
ArgumentOutOfRangeException | Bad index in a List or Substring |
NullReferenceException | Using an object that is null |
KeyNotFoundException | Missing Dictionary key |
FileNotFoundException | Reading a file that doesn't exist |
finally and the exception message
try
{
int[] pages = new int[3];
pages[5] = 1;
}
catch (Exception e)
{
Console.WriteLine($"Error: {e.Message}");
}
finally
{
Console.WriteLine("Cleanup done.");
}
Output
Error: Index was outside the bounds of the array. Cleanup done.
finally always runs, error or not. catch (Exception e) catches any exception; put specific catches first and general ones last.
throw: your own errors
void SetGrade(int grade)
{
if (grade < 0 || grade > 100)
throw new ArgumentOutOfRangeException(nameof(grade), "Grade must be from 0 to 100.");
Console.WriteLine($"Grade set to {grade}");
}
try
{
SetGrade(88);
SetGrade(150);
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine(e.Message);
}
Output
Grade set to 88 Grade must be from 0 to 100. (Parameter 'grade')
Prefer TryParse over exceptions for input
Exceptions are for unexpected problems. For user input, which is expected to be wrong sometimes, int.TryParse is cleaner and faster than catching FormatException.
Writing and reading files
string path = "students.txt";
File.WriteAllLines(path, new[] { "Ana,91", "Ben,84", "Carla,95" });
File.AppendAllText(path, "Dan,88" + Environment.NewLine);
foreach (string line in File.ReadAllLines(path))
{
string[] parts = line.Split(',');
Console.WriteLine($"{parts[0],-6}{parts[1]}");
}
Console.WriteLine($"Exists: {File.Exists(path)}");
Output
Ana 91 Ben 84 Carla 95 Dan 88 Exists: True
| Method | Does |
|---|---|
File.WriteAllText(path, text) | Writes text, replacing the file |
File.WriteAllLines(path, lines) | Writes each string as a line |
File.AppendAllText(path, text) | Adds to the end |
File.ReadAllText(path) | Reads everything as one string |
File.ReadAllLines(path) | Reads lines into a string array |
File.Exists(path) | true if the file is there |
Handling a missing file
try
{
string data = File.ReadAllText("highscore.txt");
Console.WriteLine($"High score: {data}");
}
catch (FileNotFoundException)
{
Console.WriteLine("No high score yet. Starting at 0.");
}
Output
No high score yet. Starting at 0.
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04