C#C#
IntermediateLesson 10 of 16

Error Handling & Files – C#

Exceptions, custom error types and working safely with files.

Errors are raised as exceptions (throw) and handled with try/catch. finally always runs – ideal for cleanup. Catch the most specific exception types you can.

try
{
    int zahl = int.Parse("abc");
    Console.WriteLine(zahl);
}
catch (FormatException e)
{
    Console.WriteLine("Invalid number: " + e.Message);
}
finally
{
    Console.WriteLine("Always executed");
}

Custom exception classes make errors meaningful; with when you filter cases directly in the catch clause:

try
{
    Abheben(50, 100);
}
catch (KontoException e) when (e.Fehlbetrag > 0)
{
    Console.WriteLine($"Error: {e.Message} ({e.Fehlbetrag})");   // Error: Insufficient balance (50)
}

static decimal Abheben(decimal saldo, decimal betrag)
{
    if (betrag > saldo)
        throw new KontoException("Insufficient balance", betrag - saldo);
    return saldo - betrag;
}

class KontoException : Exception
{
    public decimal Fehlbetrag { get; }
    public KontoException(string message, decimal fehlbetrag) : base(message)
        => Fehlbetrag = fehlbetrag;
}

You read and write files with File (short tasks) or StreamReader/StreamWriter. Resources that implement IDisposable are closed automatically by using – even when errors occur.

File.WriteAllText("notizen.txt", "Line 1\nLine 2\n");
foreach (var zeile in File.ReadLines("notizen.txt"))
    Console.WriteLine(zeile);

using (var writer = new StreamWriter("log.txt", append: true))
{
    writer.WriteLine("Entry");
}

using var reader = new StreamReader("log.txt");
Console.WriteLine(reader.ReadToEnd());

string pfad = Path.Combine("daten", "datei.txt");   // platform-independent
WarningRethrow with throw; (not throw e;) to keep the original stack trace. And do not catch Exception across the board if you cannot really handle the error.