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.");
}
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.
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.");
}
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 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.