Finally Block
Teil des Abschnitts Logik & Ablauf der C#-Journey von Coddy — Lektion 27 von 66.
Der finally-Block enthält Code, der immer ausgeführt wird, unabhängig davon, ob eine Ausnahme auftritt oder nicht, sogar wenn eine return-Anweisung in den try- oder catch-Blöcken vorhanden ist.
Erstellen Sie eine grundlegende try-catch-finally-Struktur:
try
{
// Code that might throw an exception
int result = 10 / 2;
Console.WriteLine("Result: " + result);
}
catch (DivideByZeroException ex)
{
// Code that handles the exception
Console.WriteLine("Cannot divide by zero: " + ex.Message);
}
finally
{
// Code that always executes
Console.WriteLine("This always executes");
}
Der finally-Block ist nützlich für Aufräumaufgaben wie das Schließen von Dateien oder Datenbankverbindungen:
System.IO.StreamReader file = null;
try
{
file = new System.IO.StreamReader("data.txt");
string content = file.ReadToEnd();
Console.WriteLine(content);
}
catch (System.IO.FileNotFoundException)
{
Console.WriteLine("File not found.");
}
finally
{
// Schließe immer die Datei, auch wenn eine Ausnahme aufgetreten ist
if (file != null)
{
file.Close();
}
}
Aufgabe
EinfachErstellen Sie eine Methode namens ProcessData, die:
- Einen String-Parameter annimmt, der einen Dateinamen darstellt
- Versucht, die Datei zu öffnen und ihren Inhalt zu lesen
- Den Inhalt auf die Konsole schreibt
- Ressourcen ordnungsgemäß mit einem finally-Block bereinigt
- FileNotFoundException und IOException behandelt
Wenn die Datei nicht gefunden werden kann, geben Sie aus: "ERROR: File not found: [filename]"
Wenn ein anderer IO-Fehler auftritt, geben Sie aus: "ERROR: Could not read the file: [error message]"
Geben Sie immer "File operation completed." im finally-Block aus, unabhängig davon, ob eine Ausnahme aufgetreten ist oder nicht.
Spickzettel
Der finally-Block enthält Code, der immer ausgeführt wird, egal ob eine Ausnahme auftritt oder nicht, sogar wenn eine return-Anweisung in den try- oder catch-Blöcken vorhanden ist.
Grundlegende try-catch-finally-Struktur:
try
{
// Code that might throw an exception
int result = 10 / 2;
Console.WriteLine("Result: " + result);
}
catch (DivideByZeroException ex)
{
// Code that handles the exception
Console.WriteLine("Cannot divide by zero: " + ex.Message);
}
finally
{
// Code that always executes
Console.WriteLine("This always executes");
}
Der finally-Block eignet sich gut für Aufräumaufgaben wie das Schließen von Dateien oder Datenbankverbindungen:
System.IO.StreamReader file = null;
try
{
file = new System.IO.StreamReader("data.txt");
string content = file.ReadToEnd();
Console.WriteLine(content);
}
catch (System.IO.FileNotFoundException)
{
Console.WriteLine("File not found.");
}
finally
{
// Always close the file, even if an exception occurred
if (file != null)
{
file.Close();
}
}
Probier es selbst
using System;
using System.IO;
class Program
{
public static void ProcessData(string filename)
{
// Schreibe deinen Code hier
}
static void Main(string[] args)
{
string filename = Console.ReadLine();
ProcessData(filename);
}
}Diese Lektion enthält ein kurzes Quiz. Starte die Lektion, um es zu beantworten und deinen Fortschritt zu speichern.
Alle Lektionen in Logik & Ablauf
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety