The throw
keyword is used to raise and propagate exceptions in the code. When a throw
statement is encountered, it stops the normal flow of execution and transfers control to the nearest matching catch
block or, if no matching catch
block is found, it terminates the program with an unhandled exception.
Here's how you can use the throw
keyword:
public void Divide(int dividend, int divisor)
{
if (divisor == 0)
{
throw new ArgumentException("Divisor cannot be zero.");
}
int result = dividend / divisor;
Console.WriteLine($"Result: {result}");
}
In this example, the Divide
method takes two integer parameters, dividend
and divisor
. Before performing the division, it checks if the divisor
is zero. If it is, the method throws an ArgumentException
with a descriptive error message.
The throw
statement is commonly used in exception handling to signal errors or exceptional conditions in the program. When an exception is thrown, the program can respond appropriately, such as by catching and handling the exception or propagating it to higher-level code for handling.
Here's an example of handling the exception thrown by the Divide
method:
try
{
Divide(10, 0);
}
catch (ArgumentException ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
In this case, the catch
block catches the ArgumentException
thrown by the Divide
method and displays the error message.
Using throw
allows you to create more robust and error-tolerant code by signaling and handling exceptions when unexpected conditions or errors occur during program execution.