Error Handling in C#

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:

  • Provide meaningful feedback to users.
  • Prevent crashes.
  • Recover from unexpected conditions.

Common Exceptions in C# Here are a few common exceptions you may encounter:

  • NullReferenceException: Occurs when you try to use an object that hasn’t been initialized.
  • DivideByZeroException: Happens when you attempt to divide a number by zero.
  • FormatException: Raised when a conversion operation fails (e.g., converting a string to an integer).

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

  • try Block: Contains code that might throw an exception.
  • catch Block: Handles the exception and defines what to do if an error occurs.
  • finally Block: Contains code that always executes, regardless of whether an exception was thrown.

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:

  • The try block attempts to perform division.
  • The catch block handles the DivideByZeroException and displays an error message.
  • The finally block executes regardless of whether an exception occurred.


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!

SHIVANG RANA

Senior Software Engineer at WatchGuard Technologies

2 个月

Go have take this 100 day quiz https://youtube.com/shorts/I8VaW4bKbI0

回复

要查看或添加评论,请登录

Shubham Raj的更多文章

社区洞察

其他会员也浏览了