Exception Handling
Learn proper exception handling techniques for robust applications. This is a foundational concept in Microsoft application framework that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world .NET experience. Take your time with each section and practice the examples
Exception Handling Basics
Exception handling allows you to gracefully handle errors and unexpected situations in your code. It prevents application crashes and provides better user experience.. This is an essential concept that every .NET developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
Try-Catch-Finally Blocks
// Basic exception handling
try
{
int result = Divide(10, 0);
Console.WriteLine($"Result: {result}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
finally
{
Console.WriteLine("This always executes");
}
// Custom exceptions
public class CustomException : Exception
{
public CustomException(string message) : base(message) { }
public CustomException(string message, Exception innerException) : base(message, innerException) { }
}
// Throwing exceptions
public int Divide(int a, int b)
{
if (b == 0)
{
throw new DivideByZeroException("Cannot divide by zero");
}
return a / b;
}
// Using custom exceptions
public void ProcessData(string data)
{
if (string.IsNullOrEmpty(data))
{
throw new CustomException("Data cannot be null or empty");
}
try
{
// Process data
Console.WriteLine($"Processing: {data}");
}
catch (Exception ex)
{
throw new CustomException("Error processing data", ex);
}
}