Throwing Exceptions in C# Programming


In C# programming, you can use the throw keyword to explicitly generate exceptions. This is useful for signaling errors or invalid states in your application logic.

Syntax of Throwing Exceptions

The basic syntax to throw an exception is:

    throw new ExceptionType("Error message");
        

You can replace ExceptionType with a specific exception class, such as ArgumentException, InvalidOperationException, or even custom exceptions.

Step-by-Step Example

Example 1: Throwing a General Exception

This example demonstrates throwing a general exception using the Exception class.

    using System;
   class Program {
        static void Main() {
            try {
                ValidateNumber(-1);
            } catch (Exception e) {
                Console.WriteLine("Caught an exception: " + e.Message);
            }
        }
       static void ValidateNumber(int number) {
            if (number < 0) {
                throw new Exception("Number cannot be negative.");
            }
        }
    }
        

Output:

Caught an exception: Number cannot be negative.

Example 2: Throwing Specific Exceptions

In this example, a more specific exception, ArgumentException, is thrown to provide better context.

    using System;
   class Program {
        static void Main() {
            try {
                SetAge(-5);
            } catch (ArgumentException e) {
                Console.WriteLine("Error: " + e.Message);
            }
        }
       static void SetAge(int age) {
            if (age < 0) {
                throw new ArgumentException("Age must be a positive number.");
            }
        }
    }
        

Output:

Error: Age must be a positive number.

Example 3: Throwing Custom Exceptions

You can create and throw custom exceptions to define your own error scenarios.

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

Output:

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

Rethrowing Exceptions

You can rethrow an exception to propagate it to higher levels in the call stack while preserving the original stack trace:

    using System;
   class Program {
        static void Main() {
            try {
                ProcessData();
            } catch (Exception e) {
                Console.WriteLine("Caught in Main: " + e.Message);
            }
        }
       static void ProcessData() {
            try {
                throw new Exception("Data processing error.");
            } catch {
                Console.WriteLine("Error caught in ProcessData.");
                throw;
            }
        }
    }
        

Output:

Error caught in ProcessData.
Caught in Main: Data processing error.

Key Points

  • Use the throw keyword to signal an error or invalid state.
  • Always provide meaningful messages to make debugging easier.
  • Throw specific exceptions where possible to provide better error context.
  • Create custom exceptions for application-specific errors.

Conclusion

Throwing exceptions is a fundamental part of error handling in C#. It allows developers to manage unexpected conditions effectively and communicate meaningful error details. By using specific and custom exceptions, you can make your applications more robust and easier to debug.




Advertisement