- Author

- Name
- Nelson Silva
- Social
Introduction
When programming, we often encounter unexpected situations that can interrupt the normal execution of our code. These interruptions are commonly referred to as exceptions. In C#, exception handling is fundamental to building resilient and robust software.
What are Exceptions?
An exception in C# is an event that arises when an abnormal condition occurs during program execution. In practice, it represents an error that can be caused by various reasons, such as IO failures, logic errors, or resource access problems.
How to Handle Exceptions
try-catch Blocks
The try block contains statements that may cause an exception, while the catch block contains the code that is executed in response to an exception.
finally Block
The finally block is always executed after the try and catch blocks have run, regardless of whether an exception occurred. It is typically used for cleanup, such as closing connections or files.
using System;
namespace Base {
class Exceptions {
public void Run() {
int[] numbers = new int[5] {
1, 2, 3, 4, 5
};
try {
Console.WriteLine($"Element content: {numbers[4]}");
}
catch (Exception exception) {
Console.WriteLine("An exception occurred!");
Console.WriteLine(exception);
}
finally {
Console.WriteLine("The finally block is always executed.");
}
}
}
}
Common Exceptions in C#
NullReferenceException: Thrown when attempting to access a member of a null object.IndexOutOfRangeException: Occurs when trying to access an index outside the bounds of an array.InvalidCastException: Arises when attempting to convert a type to an incompatible one.
Conclusion
Understanding and correctly handling exceptions in C# is essential for building reliable and robust applications. By adopting proper exception handling practices, we ensure that our programs can deal with errors gracefully and inform the user appropriately.