Curriculum
Exception Handling in C# is one of the most important concepts for building robust, reliable, and professional software applications. Exception Handling in C# allows developers to handle runtime errors gracefully without causing the application to crash unexpectedly. Every professional .NET developer uses Exception Handling in C# while developing ASP.NET Core Applications, MVC Projects, Web APIs, Desktop Applications, Cloud Applications, Microservices, Mobile Applications, and Enterprise Software Systems.
Understanding Exception Handling in C# is essential because no real-world application can guarantee that errors will never occur. Users may enter invalid data, databases may become unavailable, files may be missing, or network connections may fail. Exception Handling in C# helps applications recover from these situations and continue operating correctly.
Exception Handling in C# is a mechanism used to detect, manage, and recover from runtime errors.
An exception is an unexpected event that interrupts the normal flow of program execution.
Example:
int number = 10;
int result = number / 0;
Output:
System.DivideByZeroException
Without exception handling, the application terminates abruptly.
With Exception Handling in C#, developers can manage the error gracefully.
Exception Handling in C# helps developers:
Every modern software application relies on exception handling.
An Exception is an object that represents an error occurring during program execution.
Examples include:
Exceptions are part of normal software development.
The exception handling process generally follows these steps:
Runtime error occurs.
The Common Language Runtime (CLR) creates an exception object.
The CLR searches for a matching catch block.
The catch block executes.
Application continues execution if handled properly.
This process allows applications to recover from unexpected situations.
Basic syntax:
try
{
// Risky Code
}
catch
{
// Error Handling
}
finally
{
// Cleanup Code
}
The three major components are:
The try block contains code that may generate an exception.
Example:
try
{
int a = 10;
int b = 0;
int result = a / b;
}
The runtime monitors this block for exceptions.
If an exception occurs, control immediately transfers to a catch block.
The catch block handles exceptions generated in the try block.
Example:
try
{
int result = 10 / 0;
}
catch
{
Console.WriteLine(
"Error Occurred");
}
Output:
Error Occurred
The application continues running.
The catch block can capture exception details.
Example:
try
{
int result = 10 / 0;
}
catch(Exception ex)
{
Console.WriteLine(
ex.Message);
}
Output:
Attempted to divide by zero.
The Exception object contains useful debugging information.
Provides error description.
ex.Message
Provides exception source.
ex.Source
Shows execution path.
ex.StackTrace
Contains nested exception details.
ex.InnerException
These properties are frequently used during debugging.
The finally block always executes regardless of whether an exception occurs.
Example:
try
{
Console.WriteLine(
"Try Block");
}
catch
{
Console.WriteLine(
"Catch Block");
}
finally
{
Console.WriteLine(
"Finally Block");
}
Output:
Try Block
Finally Block
The finally block is ideal for cleanup operations.
The finally block is commonly used for:
Resource cleanup is critical in enterprise applications.
try
{
Console.Write(
"Enter Age: ");
int age =
Convert.ToInt32(
Console.ReadLine());
Console.WriteLine(
age);
}
catch(Exception ex)
{
Console.WriteLine(
"Invalid Input");
}
Output:
Invalid Input
This prevents application failure due to invalid user input.
Different exceptions can be handled separately.
Example:
try
{
int[] numbers =
{1,2,3};
Console.WriteLine(
numbers[10]);
}
catch(IndexOutOfRangeException ex)
{
Console.WriteLine(
"Invalid Index");
}
catch(Exception ex)
{
Console.WriteLine(
"General Error");
}
Output:
Invalid Index
This provides more precise error handling.
Benefits:
Professional applications commonly use multiple catch blocks.
Occurs during division by zero.
Example:
int result = 10 / 0;
Occurs when data format is invalid.
Example:
int age =
Convert.ToInt32("ABC");
Occurs when accessing a null object.
Example:
string name = null;
Console.WriteLine(
name.Length);
Occurs when accessing invalid array positions.
Example:
int[] numbers =
{1,2,3};
Console.WriteLine(
numbers[10]);
Occurs when numeric limits are exceeded.
Example:
checked
{
int value =
int.MaxValue;
value++;
}
Understanding these exceptions is important for interviews and development.
A try-catch block can exist inside another try block.
Example:
try
{
try
{
int result =
10 / 0;
}
catch
{
Console.WriteLine(
"Inner Catch");
}
}
catch
{
Console.WriteLine(
"Outer Catch");
}
Output:
Inner Catch
Nested exception handling is useful in complex applications.
Example:
try
{
string data =
File.ReadAllText(
"student.txt");
}
catch(FileNotFoundException)
{
Console.WriteLine(
"File Not Found");
}
Output:
File Not Found
File operations frequently require exception handling.
Example:
try
{
// Database Connection Code
}
catch(SqlException ex)
{
Console.WriteLine(
ex.Message);
}
Database connectivity failures are common in enterprise systems.
Exception Handling in C# is heavily used in:
Example:
try
{
return Ok(data);
}
catch(Exception ex)
{
return BadRequest(
ex.Message);
}
This improves API reliability.
Good:
catch(FileNotFoundException)
{
}
Bad:
catch(Exception)
{
}
Specific exceptions provide better control.
Bad:
catch
{
}
This hides important errors.
Always record critical exceptions.
Example:
_logger.LogError(
ex.Message);
Release resources properly.
Exceptions should handle unexpected situations only.
Avoid excessive generic exception handling.
Always review exception details.
Missing logs make debugging difficult.
Do not display technical details to users.
Never silently ignore errors.
Transaction Errors
Account Validation
Payment Failures
Order Processing
Payment Gateway Errors
Inventory Issues
Patient Record Validation
Database Connectivity
Appointment Processing
Student Registration
Fee Management
Result Processing
Exception Handling in C# helps these systems operate reliably.
Exception Handling in C# is a mechanism used to manage runtime errors gracefully.
The try block contains risky code while the catch block handles exceptions.
The finally block executes regardless of whether an exception occurs.
It occurs when attempting to access members of a null object.
They allow different exceptions to be handled differently.
Exception Handling in C# is a mechanism for handling runtime errors without crashing the application.
An Exception is an object representing a runtime error.
The try block contains code that may generate exceptions.
The catch block handles exceptions generated by the try block.
The finally block executes regardless of whether an exception occurs and is used for cleanup tasks.
It improves reliability, stability, maintainability, and user experience in software applications.
WhatsApp us