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 |
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.
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.");
}
}
}
5Check the Program Result
The division fails, so the catch block prints the error message. Finally then prints its message.
Cannot divide by zero. Operation completed.
6Watch Exception Handling Execute
Follow the program as it enters try, encounters an exception, moves to catch and finally completes the operation.
⌕
⑂
⚙
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
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.
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.
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.
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.
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.