Error Handling in C#
Error handling is a fundamental concept in programming that helps you build reliable and user-friendly applications. In this section, we’ll explore how to handle errors in C# effectively, ensuring your programs run smoothly even when unexpected situations occur.
Understanding Exceptions
What Are Exceptions?
Exceptions are runtime errors that disrupt the normal flow of program execution. These errors can occur for various reasons, such as invalid user input, attempting to divide by zero, or accessing a null object.
Why Is Error Handling Important?
Handling errors gracefully ensures that your program can:
Common Exceptions in C# Here are a few common exceptions you may encounter:
Example:
int number = 10;
int divisor = 0;
int result = number / divisor; // Throws DivideByZeroException
Try, Catch, Finally Blocks
C# provides a structured way to handle exceptions using try, catch, and finally blocks.
Purpose of Each Block
Example: Handling Division by Zero
try
{
int number = 10;
int divisor = 0;
int result = number / divisor;
Console.WriteLine($"Result: {result}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: Cannot divide by zero.");
}
finally
{
Console.WriteLine("Operation complete.");
}
In this example:
领英推荐
Throwing Exceptions
In some cases, you might need to throw an exception explicitly. This can be done using the throw keyword.
Example: Throwing an Exception
void CheckAge(int age)
{
if (age < 0)
{
throw new ArgumentException("Age cannot be negative.");
}
Console.WriteLine($"Age is {age}.");
}
Creating Custom Exceptions For domain-specific scenarios, you can create custom exception classes.
Example: Custom Exception Class
class NegativeValueException : Exception
{
public NegativeValueException(string message) : base(message) { }
}
void ValidateAmount(double amount)
{
if (amount < 0)
{
throw new NegativeValueException("Amount cannot be negative.");
}
Console.WriteLine($"Amount is valid: {amount}");
}
Practical Examples
Let’s apply these concepts to real-world scenarios.
1. Handling Invalid User Input
try
{
Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine());
Console.WriteLine($"You entered: {number}");
}
catch (FormatException)
{
Console.WriteLine("Invalid input. Please enter a valid number.");
}
2. Using finally to Release Resources
StreamReader reader = null;
try
{
reader = new StreamReader("example.txt");
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found.");
}
finally
{
if (reader != null)
{
reader.Close();
Console.WriteLine("File closed.");
}
}
3. Creating and Using Custom Exceptions
class NegativeValueException : Exception
{
public NegativeValueException(string message) : base(message) { }
}
void Withdraw(double amount)
{
if (amount < 0)
{
throw new NegativeValueException("Withdrawal amount cannot be negative.");
}
Console.WriteLine($"Withdrew: {amount}");
}
try
{
Withdraw(-50);
}
catch (NegativeValueException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
By understanding and applying these error-handling techniques, you’ll be able to write more robust and user-friendly C# programs. Practice the examples above to reinforce your learning and gain confidence in managing exceptions effectively!
Senior Software Engineer at WatchGuard Technologies
2 个月Go have take this 100 day quiz https://youtube.com/shorts/I8VaW4bKbI0