An exception in C# is an event that disrupts the normal flow of a program's execution. It typically occurs when there is an error or an unexpected condition, such as trying to divide by zero, accessing an invalid array index, or attempting to open a file that doesn't exist.
Exceptions are used to handle errors gracefully, allowing the program to either recover from the error or display an appropriate message to the user.
// exceptions (dealing with exceptions or errors)
// catch errors w/o stack overflow
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]); // Error
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
The finally block in C# is part of exception handling. It is used to define a section of code that always runs, regardless of whether an exception was thrown or not in the try block. The finally block is typically used for clean-up tasks, like closing files, releasing resources, or other operations that should always happen after the execution of a try or catch block, whether or not an exception occurred.
// finally (runs regardless of exceptions)
try
{
int number = int.Parse("NotANumber"); // error
}
catch (FormatException ex)
{
Console.WriteLine($"Format Error: {ex.Message}");
}
finally
{
Console.WriteLine("Program Runs");
}
the Exception class is the base class for all exceptions. It provides a common structure for exceptions that can be thrown during the execution of a program.
try
{
int number = int.Parse("abc");
}
catch (Exception ex)
{
Console.WriteLine($"General Error: {ex.Message}");
}
The throw keyword in C# is used to throw an exception explicitly, causing the program's normal flow to be interrupted and control to be transferred to the nearest catch block that can handle the exception.
In other words, throw is how you can trigger an exception manually when a certain error condition or exceptional situation occurs. When an exception is thrown, the runtime looks for the appropriate catch block to handle it. If no catch block is found, the exception will propagate further up the call stack, and if not handled, the program may terminate.
// throw (test with actual error)
try
{
int age = -5;
if (age < 0)
{
throw new ArgumentException("Age cannot be negative");
}
}
catch(Exception ex)
{
Console.WriteLine($"Exceptoin: {ex.Message}");
}