Exception Handling in C#
Introduction
In this lesson, you will learn exception handling in C# for beginners. Exception handling helps you manage errors in a program so it does not crash.
What is Exception Handling?
Exception handling is used to handle runtime errors using try, catch, and finally blocks.
Basic Example
try
{
int a = 10;
int b = 0;
int result = a / b;
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
try, catch, finally
try
Code that may cause error
catch
Handles the error
finally
Always runs (optional)
try
{
Console.WriteLine("Try block");
}
catch
{
Console.WriteLine("Error occurred");
}
finally
{
Console.WriteLine("Always runs");
}
Common Exceptions
- DivideByZeroException
- NullReferenceException
- IndexOutOfRangeException
Real-World Use
- Prevent app crash
- Handle user input errors
- Improve application stability
Key Points
- Exception handling prevents crashes
- try-catch is used to handle errors
- finally block always executes
Internal Links
- Course Page: .NET Course for Beginners



