Custom Exceptions in C# Programming


In C# programming, you can create custom exceptions to handle specific error conditions in your application. This allows you to provide more meaningful and context-specific error messages.

Why Use Custom Exceptions?

  • To define application-specific error scenarios.
  • To make your code more readable and easier to debug.
  • To differentiate between various types of errors.

How to Create a Custom Exception

A custom exception is created by inheriting from the System.Exception class. Here is the basic syntax:

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

Step-by-Step Example

Example 1: Creating and Using a Custom Exception

This example demonstrates how to create a custom exception and use it in your code.

    using System;
   class InvalidAgeException : Exception {
        public InvalidAgeException(string message) : base(message) {}
    }
   class Program {
        static void Main() {
            try {
                SetAge(-5);
            } catch (InvalidAgeException e) {
                Console.WriteLine("Custom exception caught: " + e.Message);
            }
        }
       static void SetAge(int age) {
            if (age < 0) {
                throw new InvalidAgeException("Age cannot be negative.");
            }
            Console.WriteLine("Age set to: " + age);
        }
    }
        

Output:

Custom exception caught: Age cannot be negative.

Example 2: Adding Additional Properties to a Custom Exception

You can add custom properties to provide more context about the error.

    using System;
   class InvalidScoreException : Exception {
        public int Score { get; }
       public InvalidScoreException(string message, int score) : base(message) {
            Score = score;
        }
    }
   class Program {
        static void Main() {
            try {
                SetScore(120);
            } catch (InvalidScoreException e) {
                Console.WriteLine("Custom exception caught: " + e.Message);
                Console.WriteLine("Invalid Score: " + e.Score);
            }
        }
       static void SetScore(int score) {
            if (score < 0 || score > 100) {
                throw new InvalidScoreException("Score must be between 0 and 100.", score);
            }
            Console.WriteLine("Score set to: " + score);
        }
    }
        

Output:

Custom exception caught: Score must be between 0 and 100.
Invalid Score: 120

Example 3: Using Custom Exceptions in a Hierarchy

You can create a hierarchy of custom exceptions to handle different error scenarios more effectively.

    using System;
   class ApplicationException : Exception {
        public ApplicationException(string message) : base(message) {}
    }
   class DatabaseException : ApplicationException {
        public DatabaseException(string message) : base(message) {}
    }
   class NetworkException : ApplicationException {
        public NetworkException(string message) : base(message) {}
    }
   class Program {
        static void Main() {
            try {
                ConnectToDatabase();
            } catch (DatabaseException e) {
                Console.WriteLine("Database error: " + e.Message);
            } catch (NetworkException e) {
                Console.WriteLine("Network error: " + e.Message);
            } catch (ApplicationException e) {
                Console.WriteLine("Application error: " + e.Message);
            }
        }
       static void ConnectToDatabase() {
            throw new DatabaseException("Unable to connect to the database.");
        }
    }
        

Output:

Database error: Unable to connect to the database.

Best Practices for Custom Exceptions

  • Always provide meaningful error messages.
  • Inherit from System.Exception or a derived class like ApplicationException.
  • Use additional properties to convey more information about the error.
  • Follow a consistent naming convention for your custom exceptions, such as ending with "Exception".

Conclusion

Custom exceptions in C# allow you to define specific error scenarios and make your applications easier to maintain and debug. By following best practices, you can create meaningful and effective custom exceptions tailored to your application.




Advertisement