Finally Block
Coddy'nin C# Journey'sinin Mantık & Akış bölümünün bir parçası — ders 27 / 66.
finally bloğu, bir istisna oluşup oluşmadığına bakılmaksızın, hatta try veya catch bloklarında bir return ifadesi olsa bile her zaman yürütülen kodu içerir.
Temel bir try-catch-finally yapısı oluşturun:
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");
}
finally bloğu, dosyaları veya veritabanı bağlantılarını kapatmak gibi temizlik görevleri için kullanışlıdır:
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
{
// Her zaman dosyayı kapat, bir istisna oluşsa bile
if (file != null)
{
file.Close();
}
}
Görev
KolayProcessData adında bir metot oluşturun ki:
- Dosya adını temsil eden bir string parametresi alsın
- Dosyayı açmayı ve içeriğini okumayı denesin
- İçeriği konsola yazsın
- finally bloğu kullanarak kaynakları düzgün bir şekilde temizlesin
- FileNotFoundException ve IOException'ı yakalasın
Dosya bulunamazsa, şunu yazdırın: "ERROR: File not found: [filename]"
Başka bir IO hatası oluşursa, şunu yazdırın: "ERROR: Could not read the file: [error message]"
Her zaman, istisna oluşsa da oluşmasa da, finally bloğunda "File operation completed." yazdırın.
Kopya kağıdı
finally bloğu, bir istisna oluşup oluşmadığına bakılmaksızın her zaman yürütülen kodu içerir, hatta try veya catch bloklarında bir return ifadesi olsa bile.
Temel try-catch-finally yapısı:
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");
}
finally bloğu, dosyaları veya veritabanı bağlantılarını kapatmak gibi temizlik görevleri için kullanışlıdır:
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();
}
}
Kendin dene
using System;
using System.IO;
class Program
{
public static void ProcessData(string filename)
{
// Buraya kodunuzu yazın
}
static void Main(string[] args)
{
string filename = Console.ReadLine();
ProcessData(filename);
}
}Bu ders kısa bir quiz içerir. Soruları yanıtlamak ve ilerlemeni kaydetmek için derse başla.
Mantık & Akış bölümündeki tüm dersler
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