Gracefully Handling Errors in C# Functions

Gracefully Handling Errors in C# Functions

Errors (also called exceptions) can happen while running a program. If we don’t handle them properly, the program may crash.

Why Handle Errors?

  • To prevent crashes
  • To give helpful messages instead of confusing errors
  • To keep the program running smoothly

In C#, we use try-catch blocks to handle errors gracefully.


1. Basic Error Handling Using try-catch

A try-catch block catches errors and allows us to handle them.

Example: Handling Division by Zero

using System;

class Program
{
    static int Divide(int a, int b)
    {
        try
        {
            return a / b;  // This may cause an error
        }
        catch (DivideByZeroException)
        {
            Console.WriteLine("Error: Cannot divide by zero!");
            return 0;  // Returning a default value
        }
    }

    static void Main()
    {
        int result = Divide(10, 0);  // Trying to divide by zero
        Console.WriteLine("Result: " + result);
    }
}        

Output :

Error : Cannot divide by zero!

Result : 0


2. Throwing Custom Errors (throw)

Sometimes, we need to generate our own errors using throw.

Example: Checking Negative Numbers

static void CheckAge(int age)
{
    if (age < 0)
    {
        throw new ArgumentException("Age cannot be negative!");
    }
    Console.WriteLine("Valid Age: " + age);
}

static void Main()
{
    try
    {
        CheckAge(-5);  // This will throw an error
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error: " + ex.Message);
    }
}        

Output :

Error: Age cannot be negative!


3. Using finally Block

The finally block always runs, whether there is an error or not.

Example: Closing a File (Even After an Error)

using System;

class Program
{
    static void Main()
    {
        try
        {
            Console.WriteLine("Opening file...");
            throw new Exception("File not found!");  // Simulating an error
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
        finally
        {
            Console.WriteLine("Closing file...");
        }
    }
}        

Output :

Opening file...

Error: File not found!

Closing file...




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

Divya Soni的更多文章