Intern
What are exceptions in the C# programming language?
sobes.tech AI
Answer from AI
Exceptions in C# are abnormal situations or errors that occur during program execution and disrupt its normal flow.
They allow separating error handling code from the main application logic and provide a more structured approach to managing errors.
Main aspects of exceptions in C#:
- Exception types: C# has a hierarchy of standard exception classes inheriting from the base class
System.Exception. For example,System.NullReferenceException,System.DivideByZeroException,System.IO.FileNotFoundException. You can also create custom exception classes. - Generating exceptions (throw): An exception is generated using the
throwkeyword. - Catching exceptions (try-catch): The
tryblock contains code that may generate an exception. Thecatchblock catches a specific type of exception and executes code to handle it. - Finally block: The
finallyblock always executes, regardless of whether an exception was thrown or not. It is often used for resource cleanup. - Using operator: A more convenient way to manage resources, which guarantees the call of the
Disposemethod. It is similar to thetry-finallyconstruct for objects implementing theIDisposableinterface. - Exception filters: Allow adding a condition to the
catchblock for more specific exception handling.
Example of usage:
public class Example
{
public void ProcessData(int denominator)
{
try
{
int result = 10 / denominator; // May generate DivideByZeroException
Console.WriteLine($"Result: {result}");
}
catch (DivideByZeroException ex) // Catching a specific exception
{
Console.WriteLine("Error: Cannot divide by zero.");
// Logging the exception if necessary
// Console.WriteLine($"Exception details: {ex.Message}");
}
catch (Exception ex) // Catching any other exception
{
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
finally // This block will always execute
{
Console.WriteLine("Processing finished.");
}
}
public void UsingExample()
{
// Example of using 'using' for automatic Dispose call
using (StreamReader reader = new StreamReader("file.txt"))
{
string line = reader.ReadLine();
Console.WriteLine(line);
} // reader.Dispose() is called automatically here, even if an exception occurs
}
public void ThrowExample(int value)
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), "Value must be non-negative."); // Generating a custom exception
}
// ... further logic
}
}
Using exceptions helps create more reliable, readable, and maintainable applications by separating error handling from the main logic.