C# Throw Keyword: Complete Usage Guide

In C#, the throw keyword is used to manually throw an exception. When certain conditions occur and the program cannot continue execution, the throw statement can be used to throw an exception, which will then be handled by the program’s exception handling mechanism. The throw statement is typically used in conjunction with a try-catch statement, where exceptions are detected in the try block and then thrown using the throw statement, ultimately caught and handled by the catch block. An example is shown below:

try
{
    int number = int.Parse(Console.ReadLine());
    if (number < 0)
    {
        throw new Exception("Number cannot be negative");
    }
}
catch (Exception ex)
{
    Console.WriteLine("An error occurred: " + ex.Message);
}

In the above example, if the user inputs a negative number, an exception with a specified error message will be thrown. The exception will be caught by a catch block and the error message will be printed out.

bannerAds