C# Keywords Tutorial Part 84: throw

C# Keywords Tutorial Part 84: throw

Popular programming language C# is frequently used to create software systems and applications. The “throw” keyword is one of C#’s features that might be helpful in managing exceptions and mistakes. This blog article will discuss the C# “throw” keyword and offer some code samples to demonstrate how to use it.

In C#, throwing an exception explicitly requires the use of the “throw” keyword. The moment an exception is thrown, the program’s execution stops and control is transferred to the first catch block that can handle the situation. The “throw” keyword in C# has the following syntax:

throw new Exception("Error message");

In the above code, we are throwing a new instance of the “Exception” class and passing an error message as a parameter. This error message will be displayed to the user when the exception is caught.

Let’s look at some examples of how to use the “throw” keyword in C#.

Example 1:

public void Divide(int x, int y)
{
    if (y == 0)
    {
        throw new DivideByZeroException("Cannot divide by zero");
    }
    int result = x / y;
    Console.WriteLine("Result: " + result);
}

In the above example, we are defining a method that takes two integers as parameters and performs a division operation. We are using the “throw” keyword to explicitly throw a “DivideByZeroException” if the second parameter is zero. This ensures that the program does not crash and displays an error message to the user instead.

Example 2:

public void Withdraw(decimal amount)
{
    if (amount > balance)
    {
        throw new ArgumentException("Insufficient balance");
    }
    balance -= amount;
    Console.WriteLine("Withdrawal successful");
}

In this example, we are defining a method that performs a withdrawal operation from a bank account. We are using the “throw” keyword to explicitly throw an “ArgumentException” if the withdrawal amount is greater than the available balance. This ensures that the program does not allow a withdrawal that could result in a negative balance.

Example 3:

public void DoSomething()
{
    try
    {
        // Code that may throw an exception
    }
    catch (Exception ex)
    {
        throw new ApplicationException("Error occurred while doing something", ex);
    }
}

In this example, we are defining a method that may throw an exception. We are using a try-catch block to catch any exceptions that may occur and re-throwing them using the “throw” keyword. We are passing the original exception as a parameter to the new “ApplicationException” that we are throwing. This ensures that the original exception information is not lost and can be used to diagnose the problem.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *