Curriculum
Exception Handling in C# is a mechanism used to detect, manage, and respond to runtime errors in applications. Exception Handling in C# helps developers prevent application crashes, improve software reliability, and provide meaningful error messages to users. Every .NET developer must understand Exception Handling in C# because it is widely used in Console Applications, ASP.NET Core Applications, MVC Projects, Web APIs, Desktop Applications, and Enterprise Software Solutions.
Real-world applications often encounter unexpected situations such as invalid user input, database connection failures, file access issues, and network problems. Exception Handling in C# helps applications handle these situations gracefully.
Exception Handling in C# is a structured way of handling runtime errors without terminating the application abruptly.
An exception is an unexpected event that occurs during program execution and disrupts normal program flow.
Example:
int number = 10;
int result = number / 0;
Output:
System.DivideByZeroException
Without proper Exception Handling in C#, the application would crash.
Exception Handling in C# helps developers:
Professional applications always implement proper exception handling mechanisms.
Syntax Errors occur during coding and are detected by the compiler.
Example:
Console.WriteLine("Hello"
Missing closing parenthesis causes a compilation error.
Logical Errors occur when the program executes but produces incorrect results.
Example:
int total = 10 - 5;
If addition was intended, the result will be incorrect.
Runtime Errors occur while the application is running.
Examples:
Exception Handling in C# is specifically designed to manage runtime errors.
Exceptions are represented by objects in C#.
Examples of common exceptions:
| Exception | Description |
|---|---|
| DivideByZeroException | Division by zero |
| FormatException | Invalid format |
| NullReferenceException | Null object access |
| IndexOutOfRangeException | Invalid array index |
| FileNotFoundException | Missing file |
| InvalidOperationException | Invalid operation |
Understanding these exceptions helps developers troubleshoot applications effectively.
The try-catch block is the most common Exception Handling mechanism in C#.
Syntax:
try
{
// risky code
}
catch
{
// error handling code
}
Example:
try
{
int result = 10 / 0;
}
catch
{
Console.WriteLine("An error occurred.");
}
Output:
An error occurred.
The application continues running instead of crashing.
Execution flow:
This process protects applications from unexpected failures.
It is recommended to handle specific exceptions whenever possible.
Example:
try
{
int result = 10 / 0;
}
catch(DivideByZeroException)
{
Console.WriteLine("Cannot divide by zero.");
}
Output:
Cannot divide by zero.
Specific exception handling improves debugging and maintainability.
Applications can handle different exceptions separately.
Example:
try
{
int age = Convert.ToInt32(Console.ReadLine());
int result = 100 / age;
}
catch(FormatException)
{
Console.WriteLine("Invalid number format.");
}
catch(DivideByZeroException)
{
Console.WriteLine("Age cannot be zero.");
}
Output depends on the type of exception encountered.
The exception object provides detailed error information.
Example:
try
{
int result = 10 / 0;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
Output:
Attempted to divide by zero.
The Message property helps identify the cause of errors.
The finally block executes regardless of whether an exception occurs.
Syntax:
try
{
}
catch
{
}
finally
{
}
Example:
try
{
Console.WriteLine("Processing");
}
catch
{
Console.WriteLine("Error");
}
finally
{
Console.WriteLine("Cleanup Complete");
}
Output:
Processing
Cleanup Complete
The finally block is commonly used for resource cleanup.
Common uses include:
These actions should occur even when exceptions happen.
Developers can catch all exceptions using the Exception class.
Example:
try
{
int result = 10 / 0;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
Although useful, handling specific exceptions is generally preferred.
Developers can create exceptions manually using throw.
Example:
int age = -5;
if(age < 0)
{
throw new Exception("Age cannot be negative.");
}
Output:
Age cannot be negative.
Custom validation often uses throw statements.
Example:
public class InvalidAgeException : Exception
{
public InvalidAgeException(string message)
: base(message)
{
}
}
Usage:
if(age < 0)
{
throw new InvalidAgeException("Invalid Age");
}
Custom exceptions improve application design and error handling.
A try-catch block can exist inside another try-catch block.
Example:
try
{
try
{
int result = 10 / 0;
}
catch(DivideByZeroException)
{
Console.WriteLine("Inner Exception");
}
}
catch
{
Console.WriteLine("Outer Exception");
}
Output:
Inner Exception
Nested handling is useful for complex applications.
try
{
ProcessTransaction();
}
catch(Exception ex)
{
Console.WriteLine("Transaction Failed");
}
try
{
File.ReadAllText("data.txt");
}
catch(FileNotFoundException)
{
Console.WriteLine("File Not Found");
}
try
{
SaveCustomer();
}
catch(Exception ex)
{
LogError(ex);
}
try
{
OpenConnection();
}
catch(SqlException)
{
Console.WriteLine("Database Error");
}
Exception Handling in C# is critical in enterprise applications.
Occurs when dividing by zero.
Occurs when accessing a null object.
Occurs during invalid type conversion.
Occurs when accessing invalid array positions.
Occurs when a file does not exist.
Understanding these exceptions helps developers write robust applications.
Exception Handling in C# is heavily used in:
A strong understanding of Exception Handling in C# helps developers create stable, secure, and professional software solutions.
Exception Handling in C# is a mechanism for managing runtime errors and preventing application crashes.
An exception is an unexpected runtime event that disrupts normal program execution.
The try-catch block allows developers to handle exceptions gracefully.
The finally block is used for cleanup operations such as closing files and database connections.
The throw keyword is used to manually generate exceptions.
It improves software stability, reliability, maintainability, and user experience.
WhatsApp us