Hayatta bazen her şeyi planlarsın ama beklenmedik bir şey olur. Yolda giderken lastik patlar, plan değişir ama yolculuk tamamen bitmez.
Yazılımda da beklenmeyen hatalar olabilir. try catch, bu hataları yakalayıp programın tamamen çökmesini önlemeye yardımcı olur.
In life, sometimes you plan everything but something unexpected happens. A tire blows out on the road; the plan changes, but the journey does not completely end.
In software, unexpected errors can also happen. try catch helps catch these errors and prevents the program from crashing completely.
try
{
int sayi = int.Parse("abc");
}
catch
{
Console.WriteLine("Bir hata oluştu.");
}
Kullanıcı yanlış veri girebilir, dosya bulunamayabilir, beklenmedik bir dönüşüm hatası olabilir. Bu gibi durumlarda programın patlaması kötü bir deneyim oluşturur.
Try catch sayesinde hatayı yönetebilir, kullanıcıya daha kontrollü bir mesaj gösterebilirsin.
The user may enter wrong data, a file may not be found, or an unexpected conversion error may occur. In such cases, having the program crash creates a poor experience.
With try catch, you can manage the error and show the user a more controlled message.
Önce riskli kod try içine yazılır. Eğer hata oluşursa akış catch bloğuna geçer.
Hata oluşmazsa catch çalışmaz ve program normal devam eder.
First, the risky code is written inside try. If an error occurs, execution moves to the catch block.
If no error occurs, catch does not run and the program continues normally.
try
{
int a = 10;
int b = 0;
Console.WriteLine(a / b);
}
catch
{
Console.WriteLine("Sıfıra bölme hatası oluştu.");
}
Bazen hata olsa da olmasa da çalışması gereken bir bölüm vardır. İşte bunun için finally kullanılır.
Örneğin bağlantı kapatma, temizlik yapma gibi işler finally içinde yer alabilir.
Sometimes there is a part that should run whether an error happens or not. That is what finally is for.
For example, tasks like closing a connection or performing cleanup can be placed inside finally.
try
{
Console.WriteLine("İşlem başladı");
}
catch
{
Console.WriteLine("Hata oluştu");
}
finally
{
Console.WriteLine("İşlem bitti");
}
Try catch çok yararlıdır ama her şeyi sessizce yutmak için kullanılmamalıdır. Amaç hatayı gizlemek değil, kontrollü yönetmektir.
Try catch is very useful, but it should not be used to silently swallow everything. The goal is not to hide the error, but to manage it in a controlled way.