Home About Lessons Blog On The Mic Contact Projects
Lessons BASIC · C#

C# Basics — Try Catch

8 min read · Emre Ulutabak
1
What is try catch?

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.

csharp
try
{
    int sayi = int.Parse("abc");
}
catch
{
    Console.WriteLine("Bir hata oluştu.");
}
💡
try represents risky code; catch represents handling the resulting error.
2
Why is it necessary?

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.

3
Error handling logic

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.

csharp
try
{
    int a = 10;
    int b = 0;
    Console.WriteLine(a / b);
}
catch
{
    Console.WriteLine("Sıfıra bölme hatası oluştu.");
}
💡
The catch block runs when an error occurs; it does not run every time.
4
Role of finally

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.

csharp
try
{
    Console.WriteLine("İşlem başladı");
}
catch
{
    Console.WriteLine("Hata oluştu");
}
finally
{
    Console.WriteLine("İşlem bitti");
}
💡
Finally runs at the end whether an error happens or not.
5
Golden rules

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.

💡
Put code inside try only when it genuinely has a chance of throwing an error.
💡
Giving the user a meaningful message inside catch is a good habit.
💡
Instead of ignoring every error, try to understand it.
MINI QUIZ
Which of the following is correct?
The catch block runs only if an error occurs
The try block is deleted when an error occurs
finally never runs
try catch is only used for arrays