A Comprehensive Resource for Microsoft Technologies

Welcome, your go-to destination for everything related to .NET and Microsoft technologies. With over 10 years of experience in the IT industry, I am excited to share my knowledge and insights on this platform. This blog is dedicated to providing valuable information, tips, and tutorials that are not only relevant to the rapidly evolving IT industry but also essential for individuals working on real-time projects and preparing for interviews

C# Tutorial 8.2: Exception Handling -Custom exceptions


C# with a focus on custom exceptions. Exception handling is a crucial aspect of writing robust and maintainable code. Custom exceptions allow you to create more meaningful and specific exception types for your application.

1. Understanding Exceptions in C#

In C#, exceptions are unexpected or exceptional events that occur during the execution of a program. These events can be errors, like dividing by zero or trying to access an array index that doesn't exist. The standard way to handle exceptions is by using try, catch, finally blocks.

try
{
    // Code that may cause an exception
}
catch (Exception ex)
{
    // Handle the exception
}
finally
{
    // Code that will always be executed, regardless of whether an exception occurred
}

2. Creating Custom Exceptions

Custom exceptions allow you to define your own exception types that better represent specific errors in your application. To create a custom exception, you need to derive a class from the Exception class.

using System;

public class CustomException : Exception
{
    public CustomException() { }

    public CustomException(string message) : base(message) { }

    public CustomException(string message, Exception innerException)
        : base(message, innerException) { }
}

3. Throwing Custom Exceptions

You can throw custom exceptions in your code when certain conditions are not met or when an error occurs.

public class Calculator
{
    public int Divide(int dividend, int divisor)
    {
        if (divisor == 0)
        {
            throw new CustomException("Cannot divide by zero.");
        }

        return dividend / divisor;
    }
}

4. Handling Custom Exceptions

Use the catch block to handle custom exceptions or any other exceptions that may occur during the execution of your code.

try
{
    Calculator calculator = new Calculator();
    int result = calculator.Divide(10, 0);
    Console.WriteLine("Result: " + result);
}
catch (CustomException ex)
{
    Console.WriteLine("Custom Exception: " + ex.Message);
}
catch (Exception ex)
{
    Console.WriteLine("An unexpected error occurred: " + ex.Message);
}
finally
{
    // Cleanup code, if needed
}

5. Best Practices

  • Use Custom Exceptions Sparingly: Only create custom exceptions when it makes sense. In many cases, the built-in exception types may be sufficient.

  • Provide Meaningful Messages: Include meaningful error messages in your custom exceptions to help developers understand the issue.

  • Consider Inner Exceptions: When creating custom exceptions, consider including an inner exception to provide more context about the error.

  • Catch Specific Exceptions: Catch specific exceptions before catching more general ones. This helps in handling different exceptions differently.

Conclusion

Exception handling is a critical part of writing reliable and robust code in C#. Custom exceptions allow you to add a layer of specificity to your error handling, making it easier to diagnose and fix issues in your application.