C# Tutorial

C# String

C# Array

C# Flow Control

C# Class and Object

C# Inheritance

C# Interface

C# Collection

C# Generic

C# File I/O

C# Delegate and Event

C# Exception

C# Process and Thread

C# ADO.NET Database Operations

C# Custom Exception (Throws An Exception)

In this tutorial, we will learn how to create a custom exception in C#. Custom exceptions allow you to define your own exception classes to handle specific situations that are unique to your application. By creating custom exceptions, you can provide more detailed information about the error, making it easier to handle and debug.

  • Creating a Custom Exception Class

To create a custom exception class, you need to inherit from the System.Exception class or one of its subclasses. In the custom exception class, you can define constructors and additional properties or methods as needed.

Here's an example of a simple custom exception class:

using System;

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

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

    public InvalidAmountException(string message, Exception inner) : base(message, inner) { }
}

In this example, we define a custom exception class called InvalidAmountException. It has three constructors: a parameterless constructor, a constructor that accepts a message, and a constructor that accepts a message and an inner exception.

  • Throwing a Custom Exception

Now that we have our custom exception class, we can throw an instance of this exception when an error occurs. Let's create a method that calculates the square of a given number. If the number is negative, we'll throw an InvalidAmountException.

public static int CalculateSquare(int number)
{
    if (number < 0)
    {
        throw new InvalidAmountException("Number must be non-negative.");
    }

    return number * number;
}

In this example, we check if the input number is negative. If it is, we throw an InvalidAmountException with a custom error message.

  • Handling a Custom Exception

To handle a custom exception, use a try-catch block as you would with any other exception. You can catch your custom exception and take appropriate action based on the error information.

Here's an example of how to handle the InvalidAmountException:

using System;

class Program
{
    static void Main(string[] args)
    {
        int[] numbers = { 4, -2, 9 };

        foreach (int number in numbers)
        {
            try
            {
                int square = CalculateSquare(number);
                Console.WriteLine($"The square of {number} is {square}");
            }
            catch (InvalidAmountException ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    }

    public static int CalculateSquare(int number)
    {
        if (number < 0)
        {
            throw new InvalidAmountException("Number must be non-negative.");
        }

        return number * number;
    }
}

In this example, we loop through an array of numbers and call the CalculateSquare method for each number. If an InvalidAmountException is thrown, we catch the exception and display the custom error message.

  • Conclusion

In this tutorial, we've learned how to create a custom exception in C#, throw it when an error occurs, and handle it using a try-catch block. Custom exceptions are useful for handling unique situations in your application and can provide more detailed information about the error, making it easier to handle and debug.

  1. C# custom exception example:

    • Description: Custom exceptions in C# allow you to create application-specific exception types tailored to your needs.
    • Code:
      public class CustomException : Exception
      {
          public CustomException(string message) : base(message)
          {
          }
      }
      
  2. How to define a custom exception in C#:

    • Description: To define a custom exception, create a class that inherits from the Exception base class.
    • Code:
      public class CustomException : Exception
      {
          // Custom properties and methods can be added here
          public CustomException(string message) : base(message)
          {
          }
      }
      
  3. Throwing custom exceptions in C#:

    • Description: Demonstrating how to throw a custom exception within a method when a specific condition is not met.
    • Code:
      public void SomeMethod(int value)
      {
          if (value < 0)
          {
              throw new CustomException("Value must be non-negative");
          }
          // Rest of the method logic
      }
      
  4. Handling custom exceptions in C#:

    • Description: Explaining how to catch and handle custom exceptions using try-catch blocks.
    • Code:
      try
      {
          SomeMethod(-1);
      }
      catch (CustomException ex)
      {
          Console.WriteLine($"Custom Exception: {ex.Message}");
      }
      
  5. Custom exception class in C#:

    • Description: Discussing the components of a custom exception class, including custom properties and methods.
    • Code:
      public class CustomException : Exception
      {
          public string ErrorCode { get; }
      
          public CustomException(string message, string errorCode) : base(message)
          {
              ErrorCode = errorCode;
          }
      }
      
  6. C# throw keyword with custom exceptions:

    • Description: Using the throw keyword to raise and propagate a custom exception in your code.
    • Code:
      public void SomeMethod(string input)
      {
          if (string.IsNullOrEmpty(input))
          {
              throw new CustomException("Input cannot be empty", "1001");
          }
          // Rest of the method logic
      }