LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
C# Programming

Exception Handling – Try, Catch and Finally

Exception handling helps us manage these situations without allowing the application to stop unexpectedly. We will understand three important keywords: try, catch and finally. These are commonly used in APIs, database operations and file processing.

1Why Do We Need Exception Handling?

Hi friends, in this article we will learn exception handling in C#. An exception is an error that occurs while a program is running. For example, dividing a number by zero or accessing a missing file can cause an exception. Exception handling helps us manage these situations without allowing the application to stop unexpectedly. We will understand three important keywords: try, catch and finally. These are commonly used in APIs, database operations and file processing.

2Think About an ATM Transaction

Imagine withdrawing money from an ATM. You enter an amount, but the bank server is temporarily unavailable. The ATM should not simply crash. It should display a proper message and allow the customer to continue safely.

In C#, the try block contains code that may fail. The catch block handles the error and provides a suitable response. The finally block runs whether an exception occurs or not.

3Understand Try, Catch and Finally

1. Try Block

Place code that might cause an exception inside try. C# monitors this code for runtime errors.

2. Catch Block

If an exception occurs, execution moves to a matching catch block. We can display a message or take corrective action.

3. Finally Block

The finally block executes after try and catch. It is commonly used for cleanup, such as releasing resources.

4. Exception Types

C# provides exception types such as FormatException, DivideByZeroException and FileNotFoundException.

Keyword Purpose
try Runs risky code
catch Handles an exception
finally Performs cleanup
Remember A catch block runs only when a matching exception occurs. Finally runs after try/catch, even when no exception occurs.

4Let's Handle a Division Error

Here, we divide two numbers. Since the denominator is zero, C# throws a DivideByZeroException. Our catch block handles it.

Program.csC#
using System;

class Program
{
    static void Main()
    {
        try
        {
            int a = 10;
            int b = 0;
            int result = a / b;

            Console.WriteLine(result);
        }
        catch (DivideByZeroException)
        {
            Console.WriteLine("Cannot divide by zero.");
        }
        finally
        {
            Console.WriteLine("Operation completed.");
        }
    }
}
Pro Tip Catch specific exception types whenever possible. This helps you handle different errors appropriately.

5Check the Program Result

The division fails, so the catch block prints the error message. Finally then prints its message.

Output
Cannot divide by zero.
Operation completed.
Common Mistake Do not use an empty catch block. It hides errors and makes debugging difficult.

6Watch Exception Handling Execute

Follow the program as it enters try, encounters an exception, moves to catch and finally completes the operation.

● ● ●Program.cs - Visual Studio Code
▸ Program.cs
▣
⌕
⑂
⚙
 
PROBLEMS  OUTPUT  DEBUG CONSOLE  TERMINAL
 
 
 
Ln 20, Col 9  UTF-8  C#

7Keep These Points in Mind

Exception handling makes applications more reliable. Use try for risky operations, catch to handle known errors and finally for cleanup. Always handle exceptions carefully and avoid hiding important error details.

  • Put risky code inside try.
  • Handle specific exceptions using catch.
  • Use finally for cleanup operations.

8Questions Interviewers May Ask

Q1Easy

What is an exception in C#?

An exception is a runtime error that interrupts normal program execution. Examples include division by zero and missing files.

Q2Easy

What is the purpose of a try block?

It contains code that may throw an exception. C# checks this code and transfers control to a matching catch block when needed.

Q3Easy

Does finally always execute?

Normally, yes. It executes after try and catch, whether an exception occurs or not. Process termination can prevent it from running.

Q4Medium

Can we have multiple catch blocks?

Yes. We can use multiple catch blocks to handle different exception types. More specific exception types should appear before general ones.

Q5Hard

What is the difference between throw and throw ex?

Inside a catch block, throw; preserves the original stack trace. throw ex; resets the stack trace information from the rethrow point.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.