C# Interview Questions

36 Questions
C# Programming

C# Programming

Web DevelopmentFrontendBackendGame Dev

Question 21

What are custom exceptions in C#?

Answer:

Custom exceptions in C# are user-defined exception classes that inherit from the base Exception class or any of its derived classes. They allow developers to create specific and meaningful exception types that are relevant to their application or domain, providing more detailed and context-specific error information than the standard exceptions.

Why Use Custom Exceptions?

  1. Clarity and Specificity:

    • Custom exceptions provide more clarity and specificity about the error condition. For example, instead of throwing a generic Exception, you can throw a FileNotFoundException or a InvalidUserInputException.
  2. Enhanced Debugging:

    • They make debugging easier by providing more context and detail about the error, which can be crucial for identifying and fixing issues.
  3. Error Handling:

    • Custom exceptions enable better error handling by allowing you to catch and handle specific exception types separately.
  4. Consistency:

    • They promote consistency in error reporting and handling across different parts of the application.

Creating Custom Exceptions

To create a custom exception, follow these steps:

  1. Inherit from the Exception Class:

    • Your custom exception should inherit from the Exception class or any of its derived classes like ApplicationException or SystemException.
  2. Implement Constructors:

    • Implement standard constructors to provide various ways to create the exception object.
  3. Optional: Add Custom Properties:

    • You can add custom properties to provide additional information about the exception.

Example of a Custom Exception

Here's an example of a custom exception called InvalidUserInputException:

using System;

public class InvalidUserInputException : Exception
{
    // Default constructor
    public InvalidUserInputException()
    {
    }

    // Constructor that accepts a custom message
    public InvalidUserInputException(string message)
        : base(message)
    {
    }

    // Constructor that accepts a custom message and an inner exception
    public InvalidUserInputException(string message, Exception inner)
        : base(message, inner)
    {
    }

    // Optional: Add custom properties
    public string UserInput { get; }

    public InvalidUserInputException(string message, string userInput)
        : base(message)
    {
        UserInput = userInput;
    }
}

// Example usage
public class Program
{
    public static void Main()
    {
        try
        {
            ProcessUserInput("Invalid Input");
        }
        catch (InvalidUserInputException ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
            Console.WriteLine($"Invalid Input: {ex.UserInput}");
        }
    }

    public static void ProcessUserInput(string input)
    {
        if (input == "Invalid Input")
        {
            throw new InvalidUserInputException("The user input is invalid.", input);
        }

        // Process the input
    }
}

Explanation

  • Class Definition:

    • The InvalidUserInputException class inherits from Exception.
    • It includes constructors for different scenarios: default, custom message, custom message with inner exception, and custom message with additional user input information.
  • Custom Properties:

    • The UserInput property holds the invalid input value, providing more context about the exception.
  • Throwing the Exception:

    • In the ProcessUserInput method, the custom exception is thrown if the input is invalid.
  • Catching the Exception:

    • In the Main method, the custom exception is caught, and the error message and invalid input are printed to the console.

Best Practices for Custom Exceptions

  1. Meaningful Names:

    • Give your custom exceptions meaningful names that clearly indicate the error condition.
  2. Standard Constructors:

    • Implement the standard exception constructors to provide flexibility in creating the exception object.
  3. Serializable:

    • Mark your custom exception class with the [Serializable] attribute if it needs to be serialized, and implement the ISerializable interface if custom serialization logic is required.
  4. Keep It Simple:

    • Avoid adding too many properties or making the custom exception too complex. Keep it focused on providing relevant error information.
  5. Document:

    • Document the custom exception class and its usage to ensure that other developers understand its purpose and how to use it correctly.

Summary

Custom exceptions in C# provide a way to create specific and meaningful error types that enhance clarity, debugging, and error handling in your applications. By inheriting from the Exception class and implementing standard constructors, you can define custom exceptions that provide additional context and information about errors, making your code more robust and maintainable.

Recent job openings